answer
stringlengths
17
10.2M
package org.literacyapp.model.enums; /** * This list represents the currently supported languages. */ public enum Locale { AR("ar"), EN("en"), // EN_US("en", "US"), ES("es"), SW("sw"); private String language; private String country; private Locale(String language) { this.language = language; } private Locale(String language, String country) { this.language = language; this.country = country; } public String getLanguage() { return language; } public String getCountry() { return country; } }
package ru.sbulygin; /** * Colculate class. * @author sbulygin. * @since 10.11.2016. * @version 1.0. */ public class Calculate { /** * Main. * @param args do not use. */ public static void main(String[] args) { System.out.println("Hello World!"); } }
package org.minimalj.backend.sql; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import org.minimalj.model.EnumUtils; import org.minimalj.model.properties.PropertyInterface; import org.minimalj.model.validation.InvalidValues; import org.minimalj.util.GenericUtils; import org.minimalj.util.IdUtils; import org.minimalj.util.ReservedSqlWords; public class SqlHelper { public static final Logger sqlLogger = Logger.getLogger("SQL"); private final SqlPersistence sqlPersistence; public SqlHelper(SqlPersistence sqlPersistence) { this.sqlPersistence = sqlPersistence; } /** * @param property the property to check * @return true if property isn't a base object like String, Integer, Date, enum but a dependable */ public static boolean isDependable(PropertyInterface property) { if (property.getClazz().getName().startsWith("java")) return false; if (Enum.class.isAssignableFrom(property.getClazz())) return false; if (property.isFinal()) return false; if (property.getClazz().isArray()) return false; return true; } public void setParameter(PreparedStatement preparedStatement, int param, Object value, PropertyInterface property) throws SQLException { if (value == null || InvalidValues.isInvalid(value)) { setParameterNull(preparedStatement, param, property); } else { if (value instanceof Enum<?>) { Enum<?> e = (Enum<?>) value; value = e.ordinal(); } else if (value instanceof LocalDate) { value = java.sql.Date.valueOf((LocalDate) value); } else if (value instanceof LocalTime) { value = java.sql.Time.valueOf((LocalTime) value); } else if (value instanceof LocalDateTime) { value = java.sql.Timestamp.valueOf((LocalDateTime) value); } else if (value instanceof Set<?>) { Set<?> set = (Set<?>) value; Class<?> enumClass = GenericUtils.getGenericClass(property.getType()); value = EnumUtils.getInt(set, enumClass); } else if (value instanceof UUID) { value = value.toString(); } preparedStatement.setObject(param, value); } } public void setParameterNull(PreparedStatement preparedStatement, int param, PropertyInterface property) throws SQLException { Class<?> clazz = property.getClazz(); if (clazz == String.class) { preparedStatement.setNull(param, Types.VARCHAR); } else if (clazz == UUID.class) { preparedStatement.setNull(param, Types.CHAR); } else if (clazz == Integer.class) { preparedStatement.setNull(param, Types.INTEGER); } else if (clazz == Boolean.class) { preparedStatement.setNull(param, Types.INTEGER); } else if (clazz == BigDecimal.class || clazz == Long.class) { preparedStatement.setNull(param, Types.DECIMAL); } else if (Enum.class.isAssignableFrom(clazz)) { preparedStatement.setNull(param, Types.INTEGER); } else if (clazz == LocalDate.class) { preparedStatement.setNull(param, Types.DATE); } else if (clazz == LocalTime.class) { preparedStatement.setNull(param, Types.TIME); } else if (clazz == LocalDateTime.class) { preparedStatement.setNull(param, Types.DATE); } else if (IdUtils.hasId(clazz)) { preparedStatement.setNull(param, Types.INTEGER); } else if (property.getClazz().isArray()) { preparedStatement.setNull(param, Types.BLOB); } else if (sqlPersistence.tableExists(clazz)) { preparedStatement.setNull(param, Types.INTEGER); } else { throw new IllegalArgumentException(clazz.getSimpleName()); } } protected Object convertToFieldClass(Class<?> fieldClass, Object value) { if (value == null) return null; if (fieldClass == LocalDate.class) { if (value instanceof java.sql.Date) { value = ((java.sql.Date) value).toLocalDate(); } else { throw new IllegalArgumentException(value.getClass().getSimpleName()); } } else if (fieldClass == LocalTime.class) { if (value instanceof java.sql.Time) { value = ((java.sql.Time) value).toLocalTime(); } else { throw new IllegalArgumentException(value.getClass().getSimpleName()); } } else if (fieldClass == LocalDateTime.class) { if (value instanceof java.sql.Timestamp) { value = ((java.sql.Timestamp) value).toLocalDateTime(); } else if (value instanceof java.sql.Date) { value = ((java.sql.Date) value).toLocalDate().atStartOfDay(); } else { throw new IllegalArgumentException(value.getClass().getSimpleName()); } } else if (fieldClass == Boolean.class) { if (value instanceof Boolean) { return value; } else if (value instanceof Integer) { value = Boolean.valueOf(((int) value) == 1); } else if (value != null) { throw new IllegalArgumentException(value.getClass().getSimpleName()); } } else if (Enum.class.isAssignableFrom(fieldClass)) { value = EnumUtils.valueList((Class<Enum>)fieldClass).get((Integer) value); } else if (fieldClass == UUID.class) { value = UUID.fromString((String) value); } return value; } public static String buildName(String name, int maxLength, Set<String> alreadyUsedNames) { name = name.toUpperCase(); name = cutToMaxLength(name, maxLength); name = avoidReservedSqlWords(name, maxLength); name = resolveNameConflicts(alreadyUsedNames, name); return name; } private static String cutToMaxLength(String fieldName, int maxLength) { if (fieldName.length() > maxLength) { fieldName = fieldName.substring(0, maxLength); } return fieldName; } private static String avoidReservedSqlWords(String fieldName, int maxLength) { if (ReservedSqlWords.reservedSqlWords.contains(fieldName)) { if (fieldName.length() == maxLength) { fieldName = fieldName.substring(0, fieldName.length() - 1); } fieldName = fieldName + "_"; } return fieldName; } private static String resolveNameConflicts(Set<String> set, String fieldName) { if (set.contains(fieldName)) { int i = 1; do { String number = Integer.toString(i); String tryFieldName = fieldName.substring(0, Math.max(fieldName.length() - number.length() - 1, 1)) + "_" + number; if (!set.contains(tryFieldName)) { fieldName = tryFieldName; break; } i++; } while (true); } return fieldName; } }
package org.ndexbio.task; import java.io.FileInputStream; import java.util.Map; import org.ndexbio.common.importexport.ExporterExecutor; import org.ndexbio.common.importexport.ImporterExporterEntry; import org.ndexbio.model.object.Status; import org.ndexbio.model.object.Task; import org.ndexbio.rest.Configuration; public class NetworkExportTask extends NdexTask { //private Task task; public NetworkExportTask(Task t) { super(t); } @Override public Task call_aux() throws Exception { Map<String, Object> attrs = task.getAttributes(); String converterName = (String)attrs.get("name"); ImporterExporterEntry entry = Configuration.getInstance().getImpExpEntry(converterName); ExporterExecutor executor = new ExporterExecutor (entry); try (FileInputStream input = new FileInputStream (Configuration.getInstance().getNdexRoot() + "/data/"+task.getResource() + "/network.cx")) { int exitCode = executor.export(input, task.getExternalId(), task.getTaskOwnerId()); if (exitCode == 0) { task.setStatus(Status.COMPLETED); } else { task.setStatus(Status.FAILED); } } return getTask(); /* System.out.println("Creating the GZIP output stream."); String outFileName = Configuration.getInstance().getNdexRoot() + "/exported-networks/" + task.getExternalId() + "." + task.getAttribute("downloadFileExtension").toString().toLowerCase() + ".gz"; try (GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFileName)) ) { try (FileInputStream in = new FileInputStream(Configuration.getInstance().getNdexRoot() + "/data/" + task.getResource() + "/network.cx")) { byte[] buf = new byte[8192]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } */ } }
package org.neo4j.util; import org.neo4j.api.core.NeoService; import org.neo4j.util.index.IndexService; import org.neo4j.util.index.LuceneIndexService; import org.neo4j.util.index.NeoIndexService; /** * Manages the life cycle of a {@link NeoService} as well as other components. * Removes the tedious work of having to think about shutting down components * and the {@link NeoService} when the JVM exists, in the right order as well. */ public class NeoServiceLifecycle { /** * Field not final since it's nulled in the shutdown process (to be able * to support multiple calls to shutdown). */ private NeoService neoService; private IndexService indexService; /** * Constructs a new {@link NeoServiceLifecycle} instance with {@code neo} * as the {@link NeoService}. Other components can be instantiated using * methods, f.ex. {@link #addIndexService(IndexService)}. * * @param neo the {@link NeoService} instance to manage. */ public NeoServiceLifecycle( NeoService neo ) { this.neoService = neo; Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { runJvmShutdownHook(); } } ); } /** * Runs the shutdown process manually instead of waiting for it to happen * just before the JVM exists, see {@link #runJvmShutdownHook()}. Normally * this method isn't necessary to call, but can be good to have for special * cases. */ public void manualShutdown() { runShutdown(); } /** * Runs the shutdown process of all started services. Supports multiple * calls to it (if such would accidentally be done). */ protected void runShutdown() { if ( this.indexService != null ) { this.indexService.shutdown(); this.indexService = null; } if ( this.neoService != null ) { this.neoService.shutdown(); this.neoService = null; } } /** * Called right before the JVM exists. It's called from a thread registered * with {@link Runtime#addShutdownHook(Thread)}. */ protected void runJvmShutdownHook() { runShutdown(); } /** * Convenience method for adding a {@link LuceneIndexService} as the * {@link IndexService}. See {@link #addIndexService(IndexService)}. * * @return the created {@link LuceneIndexService} instance. */ public IndexService addLuceneIndexService() { assertIndexServiceNotInstantiated(); return addIndexService( new LuceneIndexService( this.neoService ) ); } /** * Convenience method for adding a {@link NeoIndexService} as the * {@link IndexService}. See {@link #addIndexService(IndexService)}. * * @return the created {@link NeoIndexService} instance. */ public IndexService addNeoIndexService() { assertIndexServiceNotInstantiated(); return addIndexService( new NeoIndexService( this.neoService ) ); } /** * Adds an {@link IndexService} to list of components to manage (which * means the shutdown of it will be managed automatically). * Currently only one {@link IndexService} instance is supported so if * you try to instantiate more than one instance a * {@link UnsupportedOperationException} will be thrown. There are * convenience methods for creating common index services, * {@link #addLuceneIndexService()}, {@link #addNeoIndexService()}. * * @param indexService the {@link IndexService} to add to the list if * managed components by this life cycle object. * @return the created {@link IndexService} instance. */ public IndexService addIndexService( IndexService indexService ) { assertIndexServiceNotInstantiated(); this.indexService = indexService; return indexService; } /** * @return the {@link NeoService} instance passed in to the constructor, * {@link NeoServiceLifecycle( NeoService )}. */ public NeoService neo() { return this.neoService; } /** * @return the {@link IndexService} instance managed by this life cycle * object or {@code null} if no {@link IndexService} has been instantiated. * See {@link #addIndexService(IndexService)}. */ public IndexService indexService() { return this.indexService; } private void assertIndexServiceNotInstantiated() { if ( this.indexService != null ) { throw new UnsupportedOperationException( "This utility class " + "only supports zero or one IndexService, there's already a " + this.indexService + " instantiated" ); } } }
package org.openremote.security; import org.openremote.base.exception.IncorrectImplementationException; import org.openremote.base.exception.OpenRemoteException; import org.openremote.logging.Logger; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.security.UnrecoverableEntryException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.spec.RSAKeyGenParameterSpec; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Abstract superclass with a shared implementation to handle keystore based operations. * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public abstract class KeyManager { /** * This is the default key storage type used if nothing else is specified. Note that PKCS12 * is used for asymmetric PKI keys but not for storing symmetric secret keys. For the latter, * other provider-specific storage types must be used. <p> * * Default: {@value} */ public final static StorageType DEFAULT_KEYSTORE_STORAGE_TYPE = StorageType.PKCS12; /** * The default security provider used by this instance. Note that can contain a null value * if loading of the security provider fails. A null value should indicate using the system * installed security providers in their preferred order rather than this explicit security * provider. <p> * * Default: {@value} */ public final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC; public enum StorageType { /** * PKCS #12 format. Used to store private keys of a key pair along with its X.509 * certificate. Standardized format. */ PKCS12, JCEKS, /** * BouncyCastle keystore format roughly equivalent to Sun JKS implementation. Works with * Sun's 'keytool'. Resistant to tampering but not resistant to inspection. */ BKS, /** * Recommended BouncyCastle keystore format. Requires password verification and is * resistant to inspection and tampering. */ UBER; @Override public String toString() { return getStorageTypeName(); } public String getStorageTypeName() { return name(); } } /** * Default logger for the security package. */ protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT); /** * The key storage type used by this instance. */ private Storage storage = DEFAULT_KEYSTORE_STORAGE; /** * The storage type used by this instance. */ private StorageType storage = DEFAULT_KEYSTORE_STORAGE_TYPE; /** * Reference to the internal keystore instance that is used to persist the key entries in * this key manager. */ private KeyStore keystore = null; /** * Creates a new key manager instance with a {@link #DEFAULT_KEYSTORE_STORAGE default} key * storage format using {@link #DEFAULT_SECURITY_PROVIDER default} security provider. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager() throws ConfigurationException, KeyManagerException { this(DEFAULT_KEYSTORE_STORAGE, DEFAULT_SECURITY_PROVIDER.getProviderInstance()); } /** * This constructor allows the subclasses to specify both the key storage format and explicit * security provider to use with this instance. The key storage format and security provider * given as arguments will be used instead of the default values for this instance. <p> * * Note that the security provider parameter allows a null value. This indicates that the * appropriate security provider should be searched from the JVM installed security providers * in their preferred order. * * * @param storage * key storage format to use with this instance * * @param provider * The explicit security provider to use with the key storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(Storage storage, Provider provider) throws ConfigurationException, KeyManagerException { init(storage, provider); loadKeyStore((InputStream) null, null); } /** * This constructor will load an existing keystore into memory. It expects the keystore * to be in default key storage format as specified in {@link #DEFAULT_KEYSTORE_STORAGE}. <p> * * The URI to a keystore file must use a 'file' scheme. * * * @param keyStoreFile * a file URI pointing to a keystore file that should be loaded into this key * manager * * @param password * a master password to access the keystore file * * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(URI keyStoreFile, char[] password) throws ConfigurationException, KeyManagerException { this( keyStoreFile, password, DEFAULT_KEYSTORE_STORAGE, DEFAULT_SECURITY_PROVIDER.getProviderInstance() ); } /** * This constructor will load an existing keystore into memory. It allows the subclasses to * specify the expected key storage format used by the keystore file. The storage format * must be supported by the {@link #DEFAULT_SECURITY_PROVIDER} implementation. <p> * * The URI to a keystore file must use a 'file' scheme. * * * @param keyStoreFile * a file URI pointing to a keystore file that should be loaded into this key * manager * * @param password * a master password to access the keystore file * * @param storage * key storage format to use with this instance * * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(URI keyStoreFile, char[] password, Storage storage) throws ConfigurationException, KeyManagerException { this(keyStoreFile, password, storage, DEFAULT_SECURITY_PROVIDER.getProviderInstance()); } /** * This constructor will load an existing keystore into memory. It allows the subclasses to * specify both the expected key storage format and explicit security provider to be used * when the keystore is loaded. <p> * * Note that the security provider parameter allows a null value. This indicates that the * appropriate security provider should be searched from the JVM installed security providers * in their preferred order. <p> * * The URI to a keystore file must use a 'file' scheme. * * * @param keyStoreFile * a file URI pointing to a keystore file that should be loaded into this key * manager * * @param password * a master password to access the keystore file * * @param storage * key storage format to use with this instance * * @param provider * The explicit security provider to use with the key storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. * * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyManager(URI keyStoreFile, char[] password, Storage storage, Provider provider) throws ConfigurationException, KeyManagerException { this(storage, provider); load(keyStoreFile, password); } /** * Indicates if this key manager contains a key with a given alias. * * @param keyAlias * key alias to check * * @return true if a key is associated with a given alias in this key manager; false * otherwise */ public boolean contains(String keyAlias) { try { return keystore.containsAlias(keyAlias); } catch (KeyStoreException exception) { securityLog.error( "Unable to retrieve key info for alias '{0}' : {1}", exception, keyAlias, exception.getMessage() ); return false; } } /** * Returns the number of keys currently managed in this key manager. * * @return number of keys in this key manager */ public int size() { try { return keystore.size(); } catch (KeyStoreException exception) { securityLog.error( "Unable to retrieve keystore size : {0}", exception, exception.getMessage() ); return -1; } } /** * Initialization method used by constructors to initialize this instance. Should not be * invoked outside of a constructor. <p> * * @param storage * The keystore storage type to use with this instance. * * @param provider * The security provider to use with this instance. Can be null in which case * the implementations should delegate to the JVM installed security providers * in their preferred use order. */ protected void init(Storage storage, Provider provider) { if (storage == null) { throw new IllegalArgumentException("Implementation Error: null storage type"); } this.provider = provider; this.storage = storage; } /** * Stores the keys in this key manager in a secure key store format. This implementation generates * a file-based, persistent key store which can be shared with other applications and processes. * <p> * IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array * as soon as it is no longer needed. This prevents passwords from lingering * in JVM memory pool any longer than is necessary. Use the * {@link #clearPassword(char[])} method for this purpose. * * @param uri * The location of the file where the key store should be persisted. Must be * an URI with file scheme. * * @param password * A secret password used to access the keystore contents. NOTE: the character * array should be set to zero values after this method call completes, via * {@link #clearPassword(char[])} method. * * @see #clearPassword(char[]) * * @throws KeyManagerException * if loading or creating the keystore fails */ protected void save(URI uri, char[] password) throws ConfigurationException, KeyManagerException { if (uri == null) { throw new KeyManagerException("Save failed due to null URI."); } try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uri))); // Persist... save(keystore, out, password); } catch (FileNotFoundException exception) { throw new KeyManagerException( "File ''{0}'' cannot be created or opened : {1}", exception, resolveFilePath(new File(uri)), exception.getMessage() ); } catch (SecurityException exception) { throw new KeyManagerException( "Security manager has denied access to file ''{0}'' : {1}", exception, resolveFilePath(new File(uri)), exception.getMessage() ); } } /** * Loads existing, persisted key store contents into this instance. Any previous keys in this * key manager instance are overridden. <p> * * IMPORTANT NOTE: Subclasses that invoke this method should clear the password character array * as soon as it is no longer needed. This prevents passwords from lingering * in JVM memory pool any longer than is necessary. Use the * {@link #clearPassword(char[])} method for this purpose. * * @param uri * URI with file scheme pointing to the file system location of the keystore * to load * * @param keystorePassword * The password to access the keystore. Note that the subclasses invoking this * method are responsible for resetting the password character array after use. * * @see #clearPassword(char[]) * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading the keystore fails */ protected void load(URI uri, char[] keystorePassword) throws KeyManagerException { if (uri == null) { throw new KeyManagerException("Implementation Error: null file URI."); } loadKeyStore(new File(uri), keystorePassword); } /** * Adds a key entry to this instance. Use {@link #save(URI, char[])} to persist * if desired. * * @param keyAlias * A lookup name of the keystore entry to be added. * * @param entry * Keystore entry to be added. Note that accepted entry types depend on the * keystore storage format. * * @param param * Protection parameters for the keystore entry/alias. */ protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param) { if (keyAlias == null || keyAlias.equals("")) { throw new IllegalArgumentException( "Implementation Error: null or empty key alias is not allowed." ); } if (entry == null) { throw new IllegalArgumentException( "Implementation Error: null keystore entry is not allowed." ); } // TODO check if null protection param is ok? keyEntries.put(keyAlias, new KeyStoreEntry(entry, param)); } /** * Removes a key entry from this instance. Use {@link #save(URI, char[])} to persist * if desired. * * @param keyAlias * A lookup name of the keystore entry to be removed. * * @return true if key was removed, false otherwise */ protected boolean remove(String keyAlias) { KeyStoreEntry entry = keyEntries.remove(keyAlias); return entry != null; } /** * Returns the security provider associated with this key manager. Note that may return a * null reference in which case the implementations should delegate the functionality to * JVM installed security providers in their preferred use order. * * @return security provider instance or <tt>null</tt> */ protected Provider getSecurityProvider() { return provider; } /** * Checks if keystore exists at given file URI. * * @param uri * the file URI to check * * @return true if file exists, false otherwise * * @throws KeyManagerException * if security manager has denied access to file information */ protected boolean exists(URI uri) throws KeyManagerException { File file = new File(uri); try { return file.exists(); } catch (SecurityException e) { String path = resolveFilePath(file); throw new KeyManagerException( "Security manager has prevented access to file ''{0}'' : {1}", e, path, e.getMessage() ); } } /** * Initialization method used by constructors to initialize this instance. Should not be * invoked outside of a constructor. * * @param storage * The keystore storage type to use with this instance. * * @param provider * The security provider to use with this instance. Can be null in which case * the implementations should delegate to the JVM installed security providers * in their preferred use order. */ protected void init(StorageType storage, Provider provider) { if (storage == null) { throw new IllegalArgumentException("Implementation Error: null storage type"); } this.provider = provider; this.storage = storage; } /** * Adds the key entries of this key manager into a keystore. The keystore is saved to the given * output stream. The keystore can be an existing, loaded keystore or a new, empty one. * * @param keystore * keystore to add keys from this key manager to * * @param out * the output stream for the keystore (can be used for persisting the keystore to disk) * * @param password * password to access the keystore * * @return an in-memory keystore instance * * @throws KeyManagerException * if the save operation fails */ private KeyStore save(KeyStore keystore, OutputStream out, char[] password) throws KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } BufferedOutputStream bout = new BufferedOutputStream(out); try { for (String keyAlias : keyEntries.keySet()) { KeyStoreEntry entry = keyEntries.get(keyAlias); keystore.setEntry(keyAlias, entry.entry, entry.protectionParameter); } keystore.store(bout, password); return keystore; } catch (KeyStoreException e) { throw new KeyManagerException("Storing the key pair failed : {0}", e, e.getMessage()); } catch (IOException e) { throw new KeyManagerException( "Unable to write key to keystore : {0}", e, e.getMessage() ); } catch (NoSuchAlgorithmException e) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", e, e.getMessage() ); } catch (CertificateException e) { throw new KeyManagerException("Cannot store certificate: {0}", e, e.getMessage()); } finally { if (bout != null) { try { bout.flush(); bout.close(); } catch (IOException e) { securityLog.warn("Failed to close file output stream to keystore : {0}", e, e.getMessage()); } } } } /** * Loads a keystore instance from an existing file URI. * * @param uri * file URI to load the keystore from * * @param password * password to access the keystore * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(URI uri, char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(new File(uri), password, storage); } /** * Loads a keystore instance from an existing file. * * @param file * file to load the keystore from * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(File file, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { if (file == null) { throw new KeyManagerException("Implementation Error: null file descriptor."); } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); return getKeyStore(in, password, type); } catch (FileNotFoundException e) { throw new KeyManagerException( "Keystore file ''{0}'' could not be created or opened : {1}", e, resolveFilePath(file), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to keystore file ''{0}'' : {1}", e, resolveFilePath(file), e.getMessage() ); } } /** * Loads a key store from input stream (or creates a new, empty one). The keystore storage * format can be provided as a parameter. * * @param in * input stream to keystore file (or null to create a new one) * * @param password * shared secret (a password) used for protecting access to the keystore * * @param type * the algorithm used to securely store the keystore data * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore getKeyStore(InputStream in, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { try { KeyStore keystore; if (provider == null) { keystore = KeyStore.getInstance(type.name()); } else { keystore = KeyStore.getInstance(type.name(), provider); } keystore.load(in, password); return keystore; } catch (KeyStoreException e) { // NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested // NoSuchAlgorithmException. This is the behavior for both SUN default provider // in Java 6 and BouncyCastle. if (e.getCause() != null && e.getCause() instanceof NoSuchAlgorithmException) { String usedProviders; if (provider == null) { usedProviders = Arrays.toString(Security.getProviders()); } else { usedProviders = provider.getName(); } throw new ConfigurationException( "The security provider(s) ''{0}'' do not support keystore type ''{1}'' : {2}", e, usedProviders, type.name(), e.getMessage() ); } throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } catch (NoSuchAlgorithmException e) { // If part of the keystore load() the algorithm to verify the keystore contents cannot // be found... throw new KeyManagerException( "Required keystore verification algorithm not found: {0}", e, e.getMessage() ); } catch (CertificateException e) { // Can happen if any of the certificates in the store cannot be loaded... throw new KeyManagerException("Can't load keystore: {0}", e, e.getMessage()); } catch (IOException e) { // If there's an I/O problem, or if keystore has been corrupted, or if password is missing // if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) // // The Java 6 javadoc claims that an incorrect password can be detected by having // // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't // // seem to be the case or is not working... incorrect password is reported as an // // IOException just like other I/O errors with no root causes as far as I'm able to // // tell. So leaving this out for now // // [JPL] // throw new PasswordException( // "Cannot recover keys from keystore (was the provided password correct?) : {0}", // e.getMessage(), e throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } } /** * File utility to print file path. * * @param file * file path to print * * @return resolves to an absolute file path if allowed by the security manager, if not * returns the file path as defined in the file object parameter */ private String resolveFilePath(File file) { try { return file.getAbsolutePath(); } catch (SecurityException e) { return file.getPath(); } } /** * Convenience class to hold keystore entry and its protection parameter as single entity in * collections. */ private static class KeyStoreEntry { private KeyStore.Entry entry; private KeyStore.ProtectionParameter protectionParameter; private KeyStoreEntry(KeyStore.Entry entry, KeyStore.ProtectionParameter param) { this.entry = entry; this.protectionParameter = param; } } /** * Exception type for the public API of this class to indicate errors. */ public static class KeyManagerException extends OpenRemoteException { protected KeyManagerException(String msg) { super(msg); } protected KeyManagerException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } /** * Specific subclass of KeyManagerException that indicates a security configuration issue. */ public static class ConfigurationException extends KeyManagerException { protected ConfigurationException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } }
package org.openremote.security; import org.openremote.exception.OpenRemoteException; import org.openremote.logging.Logger; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Abstract superclass with a shared implementation to handle keystore based operations. * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public abstract class KeyManager { /** * This is the default key storage type used if nothing else is specified. Note that PKCS12 * is used for asymmetric PKI keys but not for storing symmetric secret keys. For the latter, * other provider-specific storage types must be used. <p> * * Default: {@value} */ public final static StorageType DEFAULT_KEYSTORE_STORAGE_TYPE = StorageType.PKCS12; /** * The default security provider used by this instance. Note that can contain a null value * if loading of the security provider fails. A null value should indicate using the system * installed security providers in their preferred order rather than this explicit security * provider. <p> * * Default: {@value} */ private final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC; public enum StorageType { /** * PKCS #12 format */ PKCS12, JKS, JCEKS, /** * BouncyCastle keystore format roughly equivalent to Sun JKS implementation. */ BKS; // TODO : add the rest of BC keystore options @Override public String toString() { return getStorageTypeName(); } public String getStorageTypeName() { return name(); } } /** * Default logger for the security package. */ protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT); /** * Stores key store entries which are used when the contents of this key manager is * turned into a keystore implementation (in-memory, file-persisted, or otherwise). */ private Map<String, KeyStoreEntry> keyEntries = new HashMap<String, KeyStoreEntry>(); /** * The storage type used by this instance. */ private StorageType storage = DEFAULT_KEYSTORE_STORAGE_TYPE; /** * The security provider used by this instance. Note that may contain a null reference in * which case implementation should delegate to the the JVM installed security providers * in their preferred use order. */ private Provider provider = DEFAULT_SECURITY_PROVIDER.getProviderInstance(); /** * Empty implementation, no-args constructor limited for subclass use only. */ protected KeyManager() { } /** * This constructor allows the subclasses to specify both the storage type and explicit * security provider to use with this instance. The storage type and provider will be used * instead of the default values. <p> * * Note that the provider parameter allows a null value. This indicates that the appropriate * security provider should be searched from the JVM installed security providers in their * preferred order. * * @param storage * The storage type to use with this instance. * * @param provider * The explicit security provider to use with the storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. */ protected KeyManager(StorageType storage, Provider provider) { init(storage, provider); } /** * Stores the keys in this key manager in a secure keystore format. This implementation generates * a file-based, persistent keystore which can be shared with other applications and processes. * * @param file * the file where the keystore should be saved * * @param password * A secret password used to access the keystore contents. Note that the character * array will be set to zero values after this method call completes. * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ protected KeyStore save(File file, char[] password) throws ConfigurationException, KeyManagerException { if (file == null) { throw new KeyManagerException("Save failed due to null file descriptor."); } try { KeyStore keystore; if (exists(file)) { keystore = instantiateKeyStore(file, password); } else { keystore = instantiateKeyStore(password); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); return save(keystore, out, password); } catch (FileNotFoundException e) { throw new KeyManagerException( "File ''{0}'' cannot be created or opened : {1}", e, resolveFilePath(file), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to file ''{0}'' : {1}", e, resolveFilePath(file), e.getMessage() ); } finally { // TODO : push the password clearing responsibility to subclasses... if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } } /** * Stores the keys in this key manager in a secure keystore format. This implementation generates * an in-memory keystore that is not backed by a persistent storage. * * @param password * A secret password used to access the keystore contents. Note that the character * array will be set to zero bytes when this method completes. * * @return An in-memory keystore instance. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if the keystore creation fails for any reason */ protected KeyStore save(char[] password) throws ConfigurationException, KeyManagerException { try { KeyStore keystore = instantiateKeyStore(password); return save(keystore, new ByteArrayOutputStream(), password); } finally { // TODO : push the password clearing responsibility to subclasses... if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } } /** * Loads an existing keystore from a file. * * @param file * file descriptor pointing to the keystore * * @param keystorePassword * The password to access the keystore. Note that the subclasses invoking this * method are responsible for resetting the password character array after use. * * @return The loaded keystore instance. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading the keystore fails */ protected KeyStore load(File file, char[] keystorePassword) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(file, keystorePassword); } /** * Instantiate an in-memory, non-persistent keystore. * * @param password * Password to access the keystore. Note that the subclasses invoking this * method are responsible for resetting the password character array after use. * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyStore instantiateKeyStore(char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(password, storage); } /** * Adds a key entry to this instance. Use {@link #save(java.io.File, char[])} to persist * if desired. * * @param keyAlias * A lookup name for the keystore entry to be added. * * @param entry * Keystore entry to be added. Note that accepted entry types depend on the * keystore storage format. * * @param param * Protection parameters for the keystore entry/alias. */ protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param) { if (keyAlias == null || keyAlias.equals("")) { throw new IllegalArgumentException( "Implementation Error: null or empty key alias is not allowed." ); } if (entry == null) { throw new IllegalArgumentException( "Implementation Error: null keystore entry is not allowed." ); } // TODO check if null protection param is ok? keyEntries.put(keyAlias, new KeyStoreEntry(entry, param)); } /** * TODO * * @param keyAlias * * @return */ protected boolean remove(String keyAlias) { KeyStoreEntry entry = keyEntries.remove(keyAlias); return entry != null; } /** * TODO * * @param keyAlias * * @param f * * @param keystorePassword * * @throws KeyManagerException */ protected void remove(String keyAlias, File f, char[] keystorePassword) throws KeyManagerException { try { remove(keyAlias); KeyStore ks = instantiateKeyStore(f, keystorePassword); ks.deleteEntry(keyAlias); ks.store(new FileOutputStream(f), keystorePassword); } catch (NoSuchAlgorithmException e) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", e, e.getMessage() ); } catch (CertificateException e) { throw new KeyManagerException("Cannot remove certificate: {0}", e, e.getMessage()); } catch (FileNotFoundException e) { throw new KeyManagerException( "Error in removing key ''{0}'': {1}", e, keyAlias, e.getMessage() ); } catch (IOException e) { throw new KeyManagerException( "Unable to remove key ''{0}''. I/O error: {1}", e, keyAlias, e.getMessage() ); } catch (KeyStoreException e) { throw new KeyManagerException( "Cannot remove key ''{0}'' from keystore: {1}", e, keyAlias, e.getMessage() ); } finally { if (keystorePassword != null) { for (int i = 0; i < keystorePassword.length; ++i) { keystorePassword[i] = 0; } } } } /** * Returns the security provider associated with this key manager. Note that may return a * null reference in which case the implementations should delegate the functionality to * JVM installed security providers in their preferred use order. * * @return security provider instance or <tt>null</tt> */ protected Provider getSecurityProvider() { return provider; } /** * Checks if keystore exists at given file location. * * @param file * a keystore file to check * * @return true if file exists, false otherwise * * @throws KeyManagerException * if security manager has denied access to file information */ protected boolean exists(File file) throws KeyManagerException { // TODO Implementation Note: API should use URIs to avoid file path portability issues //File file = new File(uri); try { return file.exists(); } catch (SecurityException e) { String path = resolveFilePath(file); throw new KeyManagerException( "Security manager has prevented access to file ''{0}'' : {1}", e, path, e.getMessage() ); } } /** * Initialization method used by constructors to initialize this instance. Should not be * invoked outside of a constructor. * * @param storage * The keystore storage type to use with this instance. * * @param provider * The security provider to use with this instance. Can be null in which case * the implementations should delegate to the JVM installed security providers * in their preferred use order. */ protected void init(StorageType storage, Provider provider) { if (storage == null) { throw new IllegalArgumentException("Implementation Error: null storage type"); } this.provider = provider; this.storage = storage; } /** * Adds the key entries of this key manager into a keystore. The keystore is saved to the given * output stream. The keystore can be an existing, loaded keystore or a new, empty one. * * @param keystore * keystore to add keys from this key manager to * * @param out * the output stream for the keystore (can be used for persisting the keystore to disk) * * @param password * password to access the keystore * * @return an in-memory keystore instance * * @throws KeyManagerException * if the save operation fails */ private KeyStore save(KeyStore keystore, OutputStream out, char[] password) throws KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } BufferedOutputStream bout = new BufferedOutputStream(out); try { for (String keyAlias : keyEntries.keySet()) { KeyStoreEntry entry = keyEntries.get(keyAlias); keystore.setEntry(keyAlias, entry.entry, entry.protectionParameter); } keystore.store(bout, password); return keystore; } catch (KeyStoreException e) { throw new KeyManagerException("Storing the key pair failed : {0}", e, e.getMessage()); } catch (IOException e) { throw new KeyManagerException( "Unable to write key to keystore : {0}", e, e.getMessage() ); } catch (NoSuchAlgorithmException e) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", e, e.getMessage() ); } catch (CertificateException e) { throw new KeyManagerException("Cannot store certificate: {0}", e, e.getMessage()); } finally { if (bout != null) { try { bout.flush(); bout.close(); } catch (IOException e) { securityLog.warn("Failed to close file output stream to keystore : {0}", e, e.getMessage()); } } } } /** * Instantiate an in-memory, non-persistent keystore with a given algorithm for the storage * format. * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ private KeyStore instantiateKeyStore(char[] password, StorageType type) throws ConfigurationException, KeyManagerException { return getKeyStore(null, password, type); } /** * Loads a keystore instance from an existing file. * * @param file * file to load the keystore from * * @param password * password to access the keystore * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(File file, char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(file, password, storage); } /** * Loads a keystore instance from an existing file. * * @param file * file to load the keystore from * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(File file, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { if (file == null) { throw new KeyManagerException("Implementation Error: null file descriptor."); } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); return getKeyStore(in, password, type); } catch (FileNotFoundException e) { throw new KeyManagerException( "Keystore file ''{0}'' could not be created or opened : {1}", e, resolveFilePath(file), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to keystore file ''{0}'' : {1}", e, resolveFilePath(file), e.getMessage() ); } } /** * Loads a key store from input stream (or creates a new, empty one). The keystore storage * format can be provided as a parameter. * * @param in * input stream to keystore file (or null to create a new one) * * @param password * shared secret (a password) used for protecting access to the keystore * * @param type * the algorithm used to securely store the keystore data * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore getKeyStore(InputStream in, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } try { KeyStore keystore; if (provider == null) { keystore = KeyStore.getInstance(type.name()); } else { keystore = KeyStore.getInstance(type.name(), provider); } keystore.load(in, password); return keystore; } catch (KeyStoreException e) { // NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested // NoSuchAlgorithmException. This is the behavior for both SUN default provider // in Java 6 and BouncyCastle. if (e.getCause() != null && e.getCause() instanceof NoSuchAlgorithmException) { String usedProviders; if (provider == null) { usedProviders = Arrays.toString(Security.getProviders()); } else { usedProviders = provider.getName(); } throw new ConfigurationException( "The security provider(s) ''{0}'' do not support keystore type ''{1}'' : {2}", e, usedProviders, type.name(), e.getMessage() ); } throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } catch (NoSuchAlgorithmException e) { // If part of the keystore load() the algorithm to verify the keystore contents cannot // be found... throw new KeyManagerException( "Required keystore verification algorithm not found: {0}", e, e.getMessage() ); } catch (CertificateException e) { // Can happen if any of the certificates in the store cannot be loaded... throw new KeyManagerException("Can't load keystore: {0}", e, e.getMessage()); } catch (IOException e) { // If there's an I/O problem, or if keystore has been corrupted, or if password is missing // if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) // // The Java 6 javadoc claims that an incorrect password can be detected by having // // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't // // seem to be the case or is not working... incorrect password is reported as an // // IOException just like other I/O errors with no root causes as far as I'm able to // // tell. So leaving this out for now // // [JPL] // throw new PasswordException( // "Cannot recover keys from keystore (was the provided password correct?) : {0}", // e.getMessage(), e throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } } /** * File utility to print file path. * * @param file * file path to print * * @return resolves to an absolute file path if allowed by the security manager, if not * returns the file path as defined in the file object parameter */ private String resolveFilePath(File file) { try { return file.getAbsolutePath(); } catch (SecurityException e) { return file.getPath(); } } /** * Convenience class to hold keystore entry and its protection parameter as single entity in * collections. */ private static class KeyStoreEntry { private KeyStore.Entry entry; private KeyStore.ProtectionParameter protectionParameter; private KeyStoreEntry(KeyStore.Entry entry, KeyStore.ProtectionParameter param) { this.entry = entry; this.protectionParameter = param; } } /** * Exception type for the public API of this class to indicate errors. */ public static class KeyManagerException extends OpenRemoteException { protected KeyManagerException(String msg) { super(msg); } protected KeyManagerException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } /** * Specific subclass of KeyManagerException that indicates a security configuration issue. */ public static class ConfigurationException extends KeyManagerException { protected ConfigurationException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } }
package fi.nls.oskari.util; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import java.io.IOException; import java.io.OutputStream; import java.util.Map; public class XLSXStreamer implements TabularFileStreamer { @Override public void writeToStream(String[] headers, Object[][] data, Map<String, Object> additionalFields, OutputStream out) throws IOException { Workbook wb = new SXSSFWorkbook(); Sheet sh = wb.createSheet(); Object[] rowArray; int cellNum, rowNum = 0; Row row = sh.createRow(rowNum); Cell cell; Object value; for (cellNum = 0; cellNum < headers.length; cellNum++) { cell = row.createCell(cellNum); fillCell(cell, headers[cellNum]); } for (rowNum = 1; rowNum < data.length+1; rowNum++) { rowArray = data[rowNum-1]; row = sh.createRow(rowNum); for (cellNum = 0; cellNum < rowArray.length; cellNum++) { value = rowArray[cellNum]; cell = row.createCell(cellNum); fillCell(cell, value); } } // TODO see if additional fields can be put in metadata... if (!additionalFields.isEmpty()) { row = sh.createRow(rowNum); rowNum++; } for (Map.Entry<String, Object> entry : additionalFields.entrySet()) { row = sh.createRow(rowNum); cell = row.createCell(0); fillCell(cell, entry.getKey()); cell = row.createCell(1); fillCell(cell, entry.getValue()); rowNum++; } wb.write(out); out.flush(); out.close(); } private void fillCell(Cell cell, Object value) { if (value == null) { cell.setBlank(); } else if (value instanceof String) { cell.setCellValue((String)value); } else if (value instanceof Double) { cell.setCellValue((Double)value); } else if (value instanceof Float) { cell.setCellValue((Float)value); } else if (value instanceof Integer) { cell.setCellValue((Integer)value); } else if (value instanceof Long) { cell.setCellValue((Long)value); } else if (value instanceof Short) { cell.setCellValue((Short) value); } else if (value instanceof Boolean) { cell.setCellValue((Boolean)value); } else { // Object or an Array... cell.setCellValue(value.toString()); } } }
package org.openremote.security; import org.openremote.exception.OpenRemoteException; import org.openremote.logging.Logger; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.security.cert.CertificateException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Abstract superclass with a shared implementation to handle keystore based operations. * * @author <a href="mailto:juha@openremote.org">Juha Lindfors</a> */ public abstract class KeyManager { /** * This is the default key storage type used if nothing else is specified. Note that PKCS12 * is used for asymmetric PKI keys but not for storing symmetric secret keys. For the latter, * other provider-specific storage types must be used. <p> * * Default: {@value} */ public final static StorageType DEFAULT_KEYSTORE_STORAGE_TYPE = StorageType.PKCS12; /** * The default security provider used by this instance. Note that can contain a null value * if loading of the security provider fails. A null value should indicate using the system * installed security providers in their preferred order rather than this explicit security * provider. <p> * * Default: {@value} */ private final static SecurityProvider DEFAULT_SECURITY_PROVIDER = SecurityProvider.BC; public enum StorageType { /** * PKCS #12 format */ PKCS12, JKS, JCEKS, /** * BouncyCastle keystore format roughly equivalent to Sun JKS implementation. */ BKS; // TODO : add the rest of BC keystore options @Override public String toString() { return getStorageTypeName(); } public String getStorageTypeName() { return name(); } } /** * Default logger for the security package. */ protected final static Logger securityLog = Logger.getInstance(SecurityLog.DEFAULT); /** * Stores key store entries which are used when the contents of this key manager is * turned into a keystore implementation (in-memory, file-persisted, or otherwise). */ private Map<String, KeyStoreEntry> keyEntries = new HashMap<String, KeyStoreEntry>(); /** * The storage type used by this instance. */ private StorageType storage = DEFAULT_KEYSTORE_STORAGE_TYPE; /** * The security provider used by this instance. Note that may contain a null reference in * which case implementation should delegate to the the JVM installed security providers * in their preferred use order. */ private Provider provider = DEFAULT_SECURITY_PROVIDER.getProviderInstance(); /** * Empty implementation, no-args constructor limited for subclass use only. */ protected KeyManager() { } /** * This constructor allows the subclasses to specify both the storage type and explicit * security provider to use with this instance. The storage type and provider will be used * instead of the default values. <p> * * Note that the provider parameter allows a null value. This indicates that the appropriate * security provider should be searched from the JVM installed security providers in their * preferred order. * * @param storage * The storage type to use with this instance. * * @param provider * The explicit security provider to use with the storage of this instance. If a * null value is specified, the implementations should opt to delegate the selection * of a security provider to the JVMs installed security provider implementations. */ protected KeyManager(StorageType storage, Provider provider) { init(storage, provider); } /** * Stores the keys in this key manager in a secure keystore format. This implementation generates * a file-based, persistent keystore which can be shared with other applications and processes. * * * @param uri * The location of the file where the keystore should be persisted * * @param password * A secret password used to access the keystore contents. Note that the character * array will be set to zero values after this method call completes. * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ protected KeyStore save(URI uri, char[] password) throws ConfigurationException, KeyManagerException { if (uri == null) { throw new KeyManagerException("Save failed due to null URI."); } try { KeyStore keystore; // If already exists, load from filesystem... if (exists(uri)) { keystore = instantiateKeyStore(uri, password); } // Otherwise create as new... else { keystore = createKeyStore(password); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(uri))); // Persist... return save(keystore, out, password); } catch (FileNotFoundException e) { throw new KeyManagerException( "File ''{0}'' cannot be created or opened : {1}", e, resolveFilePath(new File(uri)), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to file ''{0}'' : {1}", e, resolveFilePath(new File(uri)), e.getMessage() ); } finally { // TODO : push the password clearing responsibility to subclasses... if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } } /** * Stores the keys in this key manager in a secure keystore format. This implementation generates * an in-memory keystore that is not backed by a persistent storage. * * @param password * A secret password used to access the keystore contents. Note that the character * array will be set to zero bytes when this method completes. * * @return An in-memory keystore instance. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if the keystore creation fails for any reason */ protected KeyStore save(char[] password) throws ConfigurationException, KeyManagerException { try { KeyStore keystore = createKeyStore(password); return save(keystore, new ByteArrayOutputStream(), password); } finally { // TODO : push the password clearing responsibility to subclasses... if (password != null) { for (int i = 0; i < password.length; ++i) { password[i] = 0; } } } } /** * Loads an existing keystore from a file. * * * @param uri * file URI pointing to the location of the keystore to load * * @param keystorePassword * The password to access the keystore. Note that the subclasses invoking this * method are responsible for resetting the password character array after use. * * @return The loaded keystore instance. * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading the keystore fails */ protected KeyStore load(URI uri, char[] keystorePassword) throws ConfigurationException, KeyManagerException { if (uri == null) { throw new KeyManagerException("Implementation Error: null file URI."); } return instantiateKeyStore(uri, keystorePassword); } /** * Creates an in-memory, non-persistent keystore. * * @param password * Password to access the keystore. Note that the subclasses invoking this * method are responsible for resetting the password character array after use. * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ protected KeyStore createKeyStore(char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(password, storage); } /** * Adds a key entry to this instance. Use {@link #save(URI, char[])} to persist * if desired. * * @param keyAlias * A lookup name for the keystore entry to be added. * * @param entry * Keystore entry to be added. Note that accepted entry types depend on the * keystore storage format. * * @param param * Protection parameters for the keystore entry/alias. */ protected void add(String keyAlias, KeyStore.Entry entry, KeyStore.ProtectionParameter param) { if (keyAlias == null || keyAlias.equals("")) { throw new IllegalArgumentException( "Implementation Error: null or empty key alias is not allowed." ); } if (entry == null) { throw new IllegalArgumentException( "Implementation Error: null keystore entry is not allowed." ); } // TODO check if null protection param is ok? keyEntries.put(keyAlias, new KeyStoreEntry(entry, param)); } /** * TODO * * @param keyAlias * * @return */ protected boolean remove(String keyAlias) { KeyStoreEntry entry = keyEntries.remove(keyAlias); return entry != null; } /** * TODO * * @param keyAlias * * @param f * * @param keystorePassword * * @throws KeyManagerException */ protected void remove(String keyAlias, File f, char[] keystorePassword) throws KeyManagerException { try { remove(keyAlias); KeyStore ks = instantiateKeyStore(f.toURI(), keystorePassword); ks.deleteEntry(keyAlias); ks.store(new FileOutputStream(f), keystorePassword); } catch (NoSuchAlgorithmException e) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", e, e.getMessage() ); } catch (CertificateException e) { throw new KeyManagerException("Cannot remove certificate: {0}", e, e.getMessage()); } catch (FileNotFoundException e) { throw new KeyManagerException( "Error in removing key ''{0}'': {1}", e, keyAlias, e.getMessage() ); } catch (IOException e) { throw new KeyManagerException( "Unable to remove key ''{0}''. I/O error: {1}", e, keyAlias, e.getMessage() ); } catch (KeyStoreException e) { throw new KeyManagerException( "Cannot remove key ''{0}'' from keystore: {1}", e, keyAlias, e.getMessage() ); } finally { if (keystorePassword != null) { for (int i = 0; i < keystorePassword.length; ++i) { keystorePassword[i] = 0; } } } } /** * Returns the security provider associated with this key manager. Note that may return a * null reference in which case the implementations should delegate the functionality to * JVM installed security providers in their preferred use order. * * @return security provider instance or <tt>null</tt> */ protected Provider getSecurityProvider() { return provider; } /** * Checks if keystore exists at given file URI. * * @param uri * the file URI to check * * @return true if file exists, false otherwise * * @throws KeyManagerException * if security manager has denied access to file information */ protected boolean exists(URI uri) throws KeyManagerException { File file = new File(uri); try { return file.exists(); } catch (SecurityException e) { String path = resolveFilePath(file); throw new KeyManagerException( "Security manager has prevented access to file ''{0}'' : {1}", e, path, e.getMessage() ); } } /** * Initialization method used by constructors to initialize this instance. Should not be * invoked outside of a constructor. * * @param storage * The keystore storage type to use with this instance. * * @param provider * The security provider to use with this instance. Can be null in which case * the implementations should delegate to the JVM installed security providers * in their preferred use order. */ protected void init(StorageType storage, Provider provider) { if (storage == null) { throw new IllegalArgumentException("Implementation Error: null storage type"); } this.provider = provider; this.storage = storage; } /** * Adds the key entries of this key manager into a keystore. The keystore is saved to the given * output stream. The keystore can be an existing, loaded keystore or a new, empty one. * * @param keystore * keystore to add keys from this key manager to * * @param out * the output stream for the keystore (can be used for persisting the keystore to disk) * * @param password * password to access the keystore * * @return an in-memory keystore instance * * @throws KeyManagerException * if the save operation fails */ private KeyStore save(KeyStore keystore, OutputStream out, char[] password) throws KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } BufferedOutputStream bout = new BufferedOutputStream(out); try { for (String keyAlias : keyEntries.keySet()) { KeyStoreEntry entry = keyEntries.get(keyAlias); keystore.setEntry(keyAlias, entry.entry, entry.protectionParameter); } keystore.store(bout, password); return keystore; } catch (KeyStoreException e) { throw new KeyManagerException("Storing the key pair failed : {0}", e, e.getMessage()); } catch (IOException e) { throw new KeyManagerException( "Unable to write key to keystore : {0}", e, e.getMessage() ); } catch (NoSuchAlgorithmException e) { throw new KeyManagerException( "Security provider does not support required key store algorithm: {0}", e, e.getMessage() ); } catch (CertificateException e) { throw new KeyManagerException("Cannot store certificate: {0}", e, e.getMessage()); } finally { if (bout != null) { try { bout.flush(); bout.close(); } catch (IOException e) { securityLog.warn("Failed to close file output stream to keystore : {0}", e, e.getMessage()); } } } } /** * Instantiate an in-memory, non-persistent keystore with a given algorithm for the storage * format. * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if creating the keystore fails */ private KeyStore instantiateKeyStore(char[] password, StorageType type) throws ConfigurationException, KeyManagerException { return getKeyStore(null, password, type); } /** * Loads a keystore instance from an existing file URI. * * @param uri * file URI to load the keystore from * * @param password * password to access the keystore * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(URI uri, char[] password) throws ConfigurationException, KeyManagerException { return instantiateKeyStore(new File(uri), password, storage); } /** * Loads a keystore instance from an existing file. * * @param file * file to load the keystore from * * @param password * password to access the keystore * * @param type * the algorithm used to store the keystore data * * @return in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore instantiateKeyStore(File file, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { if (file == null) { throw new KeyManagerException("Implementation Error: null file descriptor."); } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); return getKeyStore(in, password, type); } catch (FileNotFoundException e) { throw new KeyManagerException( "Keystore file ''{0}'' could not be created or opened : {1}", e, resolveFilePath(file), e.getMessage() ); } catch (SecurityException e) { throw new KeyManagerException( "Security manager has denied access to keystore file ''{0}'' : {1}", e, resolveFilePath(file), e.getMessage() ); } } /** * Loads a key store from input stream (or creates a new, empty one). The keystore storage * format can be provided as a parameter. * * @param in * input stream to keystore file (or null to create a new one) * * @param password * shared secret (a password) used for protecting access to the keystore * * @param type * the algorithm used to securely store the keystore data * * @return an in-memory keystore instance * * @throws ConfigurationException * if the configured security provider(s) do not contain implementation for the * required keystore type * * @throws KeyManagerException * if loading or creating the keystore fails */ private KeyStore getKeyStore(InputStream in, char[] password, StorageType type) throws ConfigurationException, KeyManagerException { if (password == null || password.length == 0) { throw new KeyManagerException( "Null or empty password. Keystore must be protected with a password." ); } try { KeyStore keystore; if (provider == null) { keystore = KeyStore.getInstance(type.name()); } else { keystore = KeyStore.getInstance(type.name(), provider); } keystore.load(in, password); return keystore; } catch (KeyStoreException e) { // NOTE: If the algorithm is not recognized by a provider, it is indicated by a nested // NoSuchAlgorithmException. This is the behavior for both SUN default provider // in Java 6 and BouncyCastle. if (e.getCause() != null && e.getCause() instanceof NoSuchAlgorithmException) { String usedProviders; if (provider == null) { usedProviders = Arrays.toString(Security.getProviders()); } else { usedProviders = provider.getName(); } throw new ConfigurationException( "The security provider(s) ''{0}'' do not support keystore type ''{1}'' : {2}", e, usedProviders, type.name(), e.getMessage() ); } throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } catch (NoSuchAlgorithmException e) { // If part of the keystore load() the algorithm to verify the keystore contents cannot // be found... throw new KeyManagerException( "Required keystore verification algorithm not found: {0}", e, e.getMessage() ); } catch (CertificateException e) { // Can happen if any of the certificates in the store cannot be loaded... throw new KeyManagerException("Can't load keystore: {0}", e, e.getMessage()); } catch (IOException e) { // If there's an I/O problem, or if keystore has been corrupted, or if password is missing // if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) // // The Java 6 javadoc claims that an incorrect password can be detected by having // // a nested UnrecoverableKeyException in the wrapping IOException -- this doesn't // // seem to be the case or is not working... incorrect password is reported as an // // IOException just like other I/O errors with no root causes as far as I'm able to // // tell. So leaving this out for now // // [JPL] // throw new PasswordException( // "Cannot recover keys from keystore (was the provided password correct?) : {0}", // e.getMessage(), e throw new KeyManagerException("Cannot load keystore: {0}", e, e.getMessage()); } } /** * File utility to print file path. * * @param file * file path to print * * @return resolves to an absolute file path if allowed by the security manager, if not * returns the file path as defined in the file object parameter */ private String resolveFilePath(File file) { try { return file.getAbsolutePath(); } catch (SecurityException e) { return file.getPath(); } } /** * Convenience class to hold keystore entry and its protection parameter as single entity in * collections. */ private static class KeyStoreEntry { private KeyStore.Entry entry; private KeyStore.ProtectionParameter protectionParameter; private KeyStoreEntry(KeyStore.Entry entry, KeyStore.ProtectionParameter param) { this.entry = entry; this.protectionParameter = param; } } /** * Exception type for the public API of this class to indicate errors. */ public static class KeyManagerException extends OpenRemoteException { protected KeyManagerException(String msg) { super(msg); } protected KeyManagerException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } /** * Specific subclass of KeyManagerException that indicates a security configuration issue. */ public static class ConfigurationException extends KeyManagerException { protected ConfigurationException(String msg, Throwable cause, Object... params) { super(msg, cause, params); } } }
package org.parboiled.transform; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.BasicValue; import org.parboiled.BaseParser; import org.parboiled.support.Var; import org.parboiled.transform.method.RuleAnnotation; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.parboiled.transform.AsmUtils.getClassForType; import static org.parboiled.transform.AsmUtils.isActionRoot; import static org.parboiled.transform.AsmUtils.isAssignableTo; import static org.parboiled.transform.AsmUtils.isBooleanValueOfZ; import static org.parboiled.transform.AsmUtils.isVarRoot; import static org.parboiled.transform.method.RuleAnnotation.*; public class RuleMethod extends MethodNode { private final List<InstructionGroup> groups = new ArrayList<InstructionGroup>(); private final List<LabelNode> usedLabels = new ArrayList<LabelNode>(); private final Set<RuleAnnotation> ruleAnnotations = EnumSet .noneOf(RuleAnnotation.class); private final Class<?> ownerClass; private final int parameterCount; private boolean containsImplicitActions; // calls to Boolean.valueOf(boolean) private boolean containsExplicitActions; // calls to BaseParser.ACTION(boolean) private boolean containsVars; // calls to Var.<init>(T) private boolean containsPotentialSuperCalls; private boolean hasDontExtend; private boolean hasExplicitActionOnlyAnnotation; private boolean hasCachedAnnotation; private boolean hasDontLabelAnnotation; private boolean hasSuppressNodeAnnotation; private boolean hasSuppressSubnodesAnnotation; private boolean hasSkipNodeAnnotation; private boolean hasMemoMismatchesAnnotation; private boolean hasSkipActionsInPredicatesAnnotation; private int numberOfReturns; private InstructionGraphNode returnInstructionNode; private List<InstructionGraphNode> graphNodes; private List<LocalVariableNode> localVarVariables; private boolean bodyRewritten; private boolean skipGeneration; public RuleMethod(final Class<?> ownerClass, final int access, final String name, final String desc, final String signature, final String[] exceptions, final boolean hasExplicitActionOnlyAnno, final boolean hasDontLabelAnno, final boolean hasSkipActionsInPredicates) { super(Opcodes.ASM4, access, name, desc, signature, exceptions); this.ownerClass = ownerClass; parameterCount = Type.getArgumentTypes(desc).length; hasCachedAnnotation = parameterCount == 0; if (hasDontLabelAnno) ruleAnnotations.add(DONT_LABEL); if (hasExplicitActionOnlyAnno) ruleAnnotations.add(EXPLICIT_ACTIONS_ONLY); if (hasSkipActionsInPredicates) ruleAnnotations.add(SKIP_ACTIONS_IN_PREDICATES); hasDontLabelAnnotation = hasDontLabelAnno; hasExplicitActionOnlyAnnotation = hasExplicitActionOnlyAnno; hasSkipActionsInPredicatesAnnotation = hasSkipActionsInPredicates; skipGeneration = isSuperMethod(); } public List<InstructionGroup> getGroups() { return groups; } public List<LabelNode> getUsedLabels() { return usedLabels; } public Class<?> getOwnerClass() { return ownerClass; } public boolean hasDontExtend() { return hasDontExtend; } public int getParameterCount() { return parameterCount; } public boolean containsImplicitActions() { return containsImplicitActions; } public void setContainsImplicitActions( final boolean containsImplicitActions) { this.containsImplicitActions = containsImplicitActions; } public boolean containsExplicitActions() { return containsExplicitActions; } public void setContainsExplicitActions( final boolean containsExplicitActions) { this.containsExplicitActions = containsExplicitActions; } public boolean containsVars() { return containsVars; } public boolean containsPotentialSuperCalls() { return containsPotentialSuperCalls; } public boolean hasCachedAnnotation() { return hasCachedAnnotation; } public boolean hasDontLabelAnnotation() { return hasDontLabelAnnotation; } public boolean hasSuppressNodeAnnotation() { return hasSuppressNodeAnnotation; } public boolean hasSuppressSubnodesAnnotation() { return hasSuppressSubnodesAnnotation; } public boolean hasSkipActionsInPredicatesAnnotation() { return hasSkipActionsInPredicatesAnnotation; } public boolean hasSkipNodeAnnotation() { return hasSkipNodeAnnotation; } public boolean hasMemoMismatchesAnnotation() { return hasMemoMismatchesAnnotation; } public int getNumberOfReturns() { return numberOfReturns; } public InstructionGraphNode getReturnInstructionNode() { return returnInstructionNode; } public void setReturnInstructionNode( final InstructionGraphNode returnInstructionNode) { this.returnInstructionNode = returnInstructionNode; } public List<InstructionGraphNode> getGraphNodes() { return graphNodes; } public List<LocalVariableNode> getLocalVarVariables() { return localVarVariables; } public boolean isBodyRewritten() { return bodyRewritten; } public void setBodyRewritten() { this.bodyRewritten = true; } public boolean isSuperMethod() { Preconditions.checkState(!name.isEmpty()); return name.charAt(0) == '$'; } public InstructionGraphNode setGraphNode(final AbstractInsnNode insn, final BasicValue resultValue, final List<BasicValue> predecessors) { if (graphNodes == null) { // initialize with a list of null values graphNodes = Lists .newArrayList(new InstructionGraphNode[instructions.size()]); } final int index = instructions.indexOf(insn); InstructionGraphNode node = graphNodes.get(index); if (node == null) { node = new InstructionGraphNode(insn, resultValue); graphNodes.set(index, node); } node.addPredecessors(predecessors); return node; } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { recordDesc(ruleAnnotations, desc); if (Types.EXPLICIT_ACTIONS_ONLY_DESC.equals(desc)) { hasExplicitActionOnlyAnnotation = true; return null; // we do not need to record this annotation } if (Types.CACHED_DESC.equals(desc)) { hasCachedAnnotation = true; return null; // we do not need to record this annotation } if (Types.SUPPRESS_NODE_DESC.equals(desc)) { hasSuppressNodeAnnotation = true; return null; // we do not need to record this annotation } if (Types.SUPPRESS_SUBNODES_DESC.equals(desc)) { hasSuppressSubnodesAnnotation = true; return null; // we do not need to record this annotation } if (Types.SKIP_NODE_DESC.equals(desc)) { hasSkipNodeAnnotation = true; return null; // we do not need to record this annotation } if (Types.MEMO_MISMATCHES_DESC.equals(desc)) { hasMemoMismatchesAnnotation = true; return null; // we do not need to record this annotation } if (Types.SKIP_ACTIONS_IN_PREDICATES_DESC.equals(desc)) { hasSkipActionsInPredicatesAnnotation = true; return null; // we do not need to record this annotation } if (Types.DONT_SKIP_ACTIONS_IN_PREDICATES_DESC.equals(desc)) { hasSkipActionsInPredicatesAnnotation = false; return null; // we do not need to record this annotation } if (Types.DONT_LABEL_DESC.equals(desc)) { hasDontLabelAnnotation = true; return null; // we do not need to record this annotation } if (Types.DONT_EXTEND_DESC.equals(desc)) { hasDontExtend = true; return null; // we do not need to record this annotation } return visible ? super.visitAnnotation(desc, true) : null; // only keep visible annotations } @Override public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { switch (opcode) { case INVOKESTATIC: if (!ruleAnnotations.contains(EXPLICIT_ACTIONS_ONLY) && isBooleanValueOfZ(owner, name, desc)) { containsImplicitActions = true; } else if (isActionRoot(owner, name)) { containsExplicitActions = true; } break; case INVOKESPECIAL: if ("<init>".equals(name)) { if (isVarRoot(owner, name, desc)) { containsVars = true; } } else if (isAssignableTo(owner, BaseParser.class)) { containsPotentialSuperCalls = true; } break; } super.visitMethodInsn(opcode, owner, name, desc); } @Override public void visitInsn(final int opcode) { if (opcode == ARETURN) numberOfReturns++; super.visitInsn(opcode); } @Override public void visitJumpInsn(final int opcode, final Label label) { usedLabels.add(getLabelNode(label)); super.visitJumpInsn(opcode, label); } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label[] labels) { usedLabels.add(getLabelNode(dflt)); for (final Label label : labels) usedLabels.add(getLabelNode(label)); super.visitTableSwitchInsn(min, max, dflt, labels); } @Override public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { usedLabels.add(getLabelNode(dflt)); for (final Label label : labels) usedLabels.add(getLabelNode(label)); super.visitLookupSwitchInsn(dflt, keys, labels); } @Override public void visitLineNumber(final int line, final Label start) { // do not record line numbers } @Override public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { // only remember the local variables of Type org.parboiled.support.Var that are not parameters if (index > parameterCount && Var.class .isAssignableFrom(getClassForType(Type.getType(desc)))) { if (localVarVariables == null) localVarVariables = new ArrayList<LocalVariableNode>(); localVarVariables.add( new LocalVariableNode(name, desc, null, null, null, index)); } } @Override public String toString() { return name; } public void moveFlagsTo(final RuleMethod method) { Preconditions.checkNotNull(method); moveTo(ruleAnnotations, method.ruleAnnotations); method.hasCachedAnnotation |= hasCachedAnnotation; method.hasDontLabelAnnotation |= hasDontLabelAnnotation; method.hasSuppressNodeAnnotation |= hasSuppressNodeAnnotation; method.hasSuppressSubnodesAnnotation |= hasSuppressSubnodesAnnotation; method.hasSkipNodeAnnotation |= hasSkipNodeAnnotation; method.hasMemoMismatchesAnnotation |= hasMemoMismatchesAnnotation; hasDontLabelAnnotation = true; hasCachedAnnotation = false; hasSuppressNodeAnnotation = false; hasSuppressSubnodesAnnotation = false; hasSkipNodeAnnotation = false; hasMemoMismatchesAnnotation = false; } public boolean isGenerationSkipped() { return skipGeneration; } public void dontSkipGeneration() { skipGeneration = false; } public void suppressNode() { hasSuppressNodeAnnotation = true; } }
// The five files // Option.java // OptionGroup.java // Options.java // Unpublicized.java // OptionsDoclet.java // together comprise the implementation of command-line processing. package org.plumelib.options; import static java.nio.charset.StandardCharsets.UTF_8; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.Doc; import com.sun.javadoc.DocErrorReporter; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.RootDoc; import com.sun.javadoc.SeeTag; import com.sun.javadoc.Tag; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.util.ArrayList; import java.util.Formatter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.StringJoiner; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.checkerframework.checker.formatter.qual.Format; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.RequiresNonNull; import org.checkerframework.checker.signature.qual.BinaryName; import org.checkerframework.common.value.qual.MinLen; // This doesn't itself use org.plumelib.options.Options for its command-line option processing // because a Doclet is // required to implement the optionLength() and validOptions() methods. @SuppressWarnings("deprecation") // JDK 9 deprecates com.sun.javadoc package public class OptionsDoclet { /** The system-specific line separator. */ private static String lineSep = System.lineSeparator(); /** How to use the Options doclet. */ @SuppressWarnings("InlineFormatString") private static final @Format({}) String USAGE = "Provided by Options doclet:%n" + "-docfile <file> Specify file into which options documentation is inserted%n" + "-outfile <file> Specify destination for resulting output%n" + "-d <directory> Destination directory for -outfile%n" + "-i Edit the docfile in-place%n" + "-format javadoc Format output as a Javadoc comment%n" + "-classdoc Include 'main' class documentation in output%n" + "-singledash Use single dashes for long options (see org.plumelib.options.Options)%n" + "See the OptionsDoclet documentation for more details.%n"; /** Help message about options that can be specified multiple times. */ private static final String LIST_HELP = "<code>[+]</code> marked option can be specified multiple times"; /** Marker for start of options documentation. */ private String startDelim = "<!-- start options doc (DO NOT EDIT BY HAND) -->"; /** Marker for end of options documentation. */ private String endDelim = "<!-- end options doc -->"; /** The file into which options documentation is inserted. */ private @Nullable File docFile = null; /** Destination for output. */ private @Nullable File outFile = null; /** If true, then edit docFile in place (and docFile is non-null). */ private boolean inPlace = false; /** If true, then output format is Javadoc. */ private boolean formatJavadoc = false; /** If true, then include the class's main Javadoc comment. */ private boolean includeClassDoc = false; /** The document root. */ private RootDoc root; /** The command-line options. */ private Options options; /** * Create an OptionsDoclet that documents the given options. * * @param root the document root * @param options the command-line options */ public OptionsDoclet(RootDoc root, Options options) { this.root = root; this.options = options; } // Doclet-specific methods /** * Entry point for the doclet. * * @param root the root document * @return true if processing completed without an error */ public static boolean start(RootDoc root) { List<Object> objs = new ArrayList<>(); for (ClassDoc doc : root.specifiedClasses()) { // TODO: Class.forName() expects a binary name but doc.qualifiedName() // returns a fully qualified name. I do not know a good way to convert // between these two name formats. For now, we simply ignore inner // classes. This limitation can be removed when we figure out a better // way to go from ClassDoc to Class<?>. if (doc.containingClass() != null) { continue; } Class<?> clazz; try { @SuppressWarnings("signature") // Javadoc source code is not yet annotated @BinaryName String className = doc.qualifiedName(); clazz = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); Options.printClassPath(); return false; } if (needsInstantiation(clazz)) { try { Constructor<?> c = clazz.getDeclaredConstructor(); c.setAccessible(true); objs.add(c.newInstance(new Object[0])); } catch (Exception e) { e.printStackTrace(); return false; } } else { objs.add(clazz); } } if (objs.isEmpty()) { System.out.println("Error: no classes found"); return false; } Object[] objarray = objs.toArray(); Options options = new Options(objarray); if (options.getOptions().size() < 1) { System.out.println("Error: no @Option-annotated fields found"); return false; } OptionsDoclet o = new OptionsDoclet(root, options); String[] @MinLen(1) [] rootOptions = root.options(); o.setOptions(rootOptions); o.processJavadoc(); try { o.write(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public static int optionLength(String option) { if (option.equals("-help")) { System.out.printf(USAGE); return 1; } if (option.equals("-i") || option.equals("-classdoc") || option.equals("-singledash")) { return 1; } if (option.equals("-docfile") || option.equals("-outfile") || option.equals("-format") || option.equals("-d")) { return 2; } return 0; } public static boolean validOptions(String[] @MinLen(1) [] options, DocErrorReporter reporter) { boolean hasDocFile = false; boolean hasOutFile = false; boolean hasDestDir = false; boolean hasFormat = false; boolean inPlace = false; String docFile = null; String outFile = null; for (int oi = 0; oi < options.length; oi++) { String[] os = options[oi]; String opt = os[0].toLowerCase(); if (opt.equals("-docfile")) { if (hasDocFile) { reporter.printError("-docfile option specified twice"); return false; } assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"docfile\")==2"; docFile = os[1]; File f = new File(docFile); if (!f.exists()) { reporter.printError("-docfile file not found: " + docFile); return false; } hasDocFile = true; } if (opt.equals("-outfile")) { if (hasOutFile) { reporter.printError("-outfile option specified twice"); return false; } if (inPlace) { reporter.printError("-i and -outfile can not be used at the same time"); return false; } assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"outfile\")==2"; outFile = os[1]; hasOutFile = true; } if (opt.equals("-i")) { if (hasOutFile) { reporter.printError("-i and -outfile can not be used at the same time"); return false; } inPlace = true; } if (opt.equals("-format")) { if (hasFormat) { reporter.printError("-format option specified twice"); return false; } assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"format\")==2"; String format = os[1]; if (!format.equals("javadoc") && !format.equals("html")) { reporter.printError("unrecognized output format: " + format); return false; } hasFormat = true; } if (opt.equals("-d")) { if (hasDestDir) { reporter.printError("-d specified twice"); return false; } hasDestDir = true; } } if (docFile != null && outFile != null && outFile.equals(docFile)) { reporter.printError("docfile must be different from outfile"); return false; } if (inPlace && docFile == null) { reporter.printError("-i supplied but -docfile was not"); return false; } return true; } /** * Set the underlying Options instance for this class based on command-line arguments given by * RootDoc.options(). * * @param options the command-line options to parse: a list of 1- or 2-element arrays */ public void setOptions(String[] @MinLen(1) [] options) { String outFilename = null; File destDir = null; for (int oi = 0; oi < options.length; oi++) { String[] os = options[oi]; String opt = os[0].toLowerCase(); if (opt.equals("-docfile")) { assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"docfile\")==2"; this.docFile = new File(os[1]); } else if (opt.equals("-d")) { assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"d\")==2"; destDir = new File(os[1]); } else if (opt.equals("-outfile")) { assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"outfile\")==2"; outFilename = os[1]; } else if (opt.equals("-i")) { this.inPlace = true; } else if (opt.equals("-format")) { assert os.length == 2 : "@AssumeAssertion(value): dependent: optionLength(\"format\")==2"; if (os[1].equals("javadoc")) { setFormatJavadoc(true); } } else if (opt.equals("-classdoc")) { this.includeClassDoc = true; } else if (opt.equals("-singledash")) { setUseSingleDash(true); } } if (outFilename != null) { if (destDir != null) { this.outFile = new File(destDir, outFilename); } else { this.outFile = new File(outFilename); } } } private static boolean needsInstantiation(Class<?> clazz) { for (Field f : clazz.getDeclaredFields()) { if (f.isAnnotationPresent(Option.class) && !Modifier.isStatic(f.getModifiers())) { return true; } } return false; } // File IO methods /** * Write the output of this doclet to the correct file. * * @throws Exception if there is trouble */ public void write() throws Exception { PrintWriter out; String output = output(); if (outFile != null) { out = new PrintWriter(Files.newBufferedWriter(outFile.toPath(), UTF_8)); } else if (inPlace) { assert docFile != null : "@AssumeAssertion(nullness): dependent: docFile is non-null if inPlace is true"; out = new PrintWriter(Files.newBufferedWriter(docFile.toPath(), UTF_8)); } else { out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out, UTF_8))); } out.println(output); out.flush(); out.close(); } /** * Get the final output of this doclet. The string returned by this method is the output seen by * the user. * * @return the user-visible doclet output * @throws Exception if there is trouble */ public String output() throws Exception { if (docFile == null) { if (formatJavadoc) { return optionsToJavadoc(0, 99); } else { return optionsToHtml(0); } } return newDocFileText(); } /** * Get the result of inserting the options documentation into the docfile. * * @return the docfile, but with the command-line argument documentation updated * @throws Exception if there is trouble reading files */ @RequiresNonNull("docFile") private String newDocFileText() throws Exception { StringJoiner b = new StringJoiner(lineSep); BufferedReader doc = Files.newBufferedReader(docFile.toPath(), UTF_8); String docline; boolean replacing = false; boolean replacedOnce = false; while ((docline = doc.readLine()) != null) { if (replacing) { if (docline.trim().equals(endDelim)) { replacing = false; } else { continue; } } b.add(docline); if (!replacedOnce && docline.trim().equals(startDelim)) { if (formatJavadoc) { int starIndex = docline.indexOf('*'); b.add(docline.substring(0, starIndex + 1)); String jdoc = optionsToJavadoc(starIndex, 100); b.add(jdoc); if (jdoc.endsWith("</ul>")) { b.add(docline.substring(0, starIndex + 1)); } } else { b.add(optionsToHtml(0)); } replacedOnce = true; replacing = true; } } if (!replacedOnce) { System.err.println("Did not find start delimiter: " + startDelim); } doc.close(); return b.toString(); } // HTML and Javadoc processing methods /** Adds Javadoc info to each option in {@code options.getOptions()}. */ public void processJavadoc() { for (Options.OptionInfo oi : options.getOptions()) { ClassDoc optDoc = root.classNamed(oi.getDeclaringClass().getName()); if (optDoc != null) { String nameWithUnderscores = oi.longName.replace('-', '_'); for (FieldDoc fd : optDoc.fields()) { if (fd.name().equals(nameWithUnderscores)) { // If Javadoc for field is unavailable, then use the @Option // description in the documentation. if (fd.getRawCommentText().length() == 0) { // Input is a string rather than a Javadoc (HTML) comment so we // must escape it. oi.jdoc = StringEscapeUtils.escapeHtml4(oi.description); } else if (formatJavadoc) { oi.jdoc = fd.commentText(); } else { oi.jdoc = javadocToHtml(fd); } break; } } } if (oi.baseType.isEnum()) { processEnumJavadoc(oi); } } } /** * Initializes {@link Options.OptionInfo#enumJdoc} for the given {@code OptionInfo}: creates a * mapping from enum constants to their Javadoc * * @param oi the enum option whose Javadoc to read */ private void processEnumJavadoc(Options.OptionInfo oi) { Enum<?>[] constants = (Enum<?>[]) oi.baseType.getEnumConstants(); if (constants == null) { return; } oi.enumJdoc = new LinkedHashMap<>(); for (Enum<?> constant : constants) { assert oi.enumJdoc != null : "@AssumeAssertion(nullness): bug in flow?"; oi.enumJdoc.put(constant.name(), ""); } ClassDoc enumDoc = root.classNamed(oi.baseType.getName()); if (enumDoc == null) { return; } assert oi.enumJdoc != null : "@AssumeAssertion(nullness): bug in flow?"; for (String name : oi.enumJdoc.keySet()) { for (FieldDoc fd : enumDoc.fields()) { if (fd.name().equals(name)) { if (formatJavadoc) { oi.enumJdoc.put(name, fd.commentText()); } else { oi.enumJdoc.put(name, javadocToHtml(fd)); } break; } } } } /** * Get the HTML documentation for the underlying Options instance. * * @param refillWidth the number of columns to fit the text into, by breaking lines * @return the HTML documentation for the underlying Options instance */ public String optionsToHtml(int refillWidth) { StringJoiner b = new StringJoiner(lineSep); if (includeClassDoc && root.classes().length > 0) { b.add(OptionsDoclet.javadocToHtml(root.classes()[0])); b.add("<p>Command line options:</p>"); } b.add("<ul>"); if (!options.hasGroups()) { b.add(optionListToHtml(options.getOptions(), 6, 2, refillWidth)); } else { for (Options.OptionGroupInfo gi : options.getOptionGroups()) { // Do not include groups without publicized options in output if (!gi.anyPublicized()) { continue; } String ogroupHeader = " <li id=\"optiongroup:" + gi.name.replace(" ", "-").replace("/", "-") + "\">" + gi.name; b.add(refill(ogroupHeader, 6, 2, refillWidth)); b.add(" <ul>"); b.add(optionListToHtml(gi.optionList, 12, 8, refillWidth)); b.add(" </ul>"); // b.add(" </li>"); } } b.add("</ul>"); for (Options.OptionInfo oi : options.getOptions()) { if (oi.list != null && !oi.unpublicized) { b.add(""); b.add(LIST_HELP); break; } } return b.toString(); } /** * Get the HTML documentation for the underlying Options instance, formatted as a Javadoc comment. * * @param padding the number of leading spaces to add in the Javadoc output, before "* " * @param refillWidth the number of columns to fit the text into, by breaking lines * @return the HTML documentation for the underlying Options instance */ public String optionsToJavadoc(int padding, int refillWidth) { StringJoiner b = new StringJoiner(lineSep); Scanner s = new Scanner(optionsToHtml(refillWidth - padding - 2)); while (s.hasNextLine()) { String line = s.nextLine(); StringBuilder bb = new StringBuilder(); bb.append(StringUtils.repeat(" ", padding)); if (line.trim().equals("")) { bb.append("*"); } else { bb.append("* ").append(line); } b.add(bb); } return b.toString(); } /** * Get the HTML describing many options, formatted as an HTML list. * * @param optList the options to document * @param padding the number of leading spaces to add before each line of HTML output, except the * first one * @param firstLinePadding the number of leading spaces to add before the first line of HTML * output * @param refillWidth the number of columns to fit the text into, by breaking lines * @return the options documented in HTML format */ private String optionListToHtml( List<Options.OptionInfo> optList, int padding, int firstLinePadding, int refillWidth) { StringJoiner b = new StringJoiner(lineSep); for (Options.OptionInfo oi : optList) { if (oi.unpublicized) { continue; } StringBuilder bb = new StringBuilder(); String optHtml = optionToHtml(oi, padding); bb.append(StringUtils.repeat(" ", padding)); bb.append("<li id=\"option:" + oi.longName + "\">").append(optHtml); // .append("</li>"); if (refillWidth <= 0) { b.add(bb); } else { b.add(refill(bb.toString(), padding, firstLinePadding, refillWidth)); } } return b.toString(); } /** * Refill the string so that each line is {@code refillWidth} characters long. * * @param in the string to refill * @param padding each line, other than the first, starts with this many spaces * @param firstLinePadding the first line starts with this many spaces * @param refillWidth the maximum width of each line in the output, including the padding * @return a string in which no more than {@code refillWidth} characters appear between any two * end-of-line character sequences */ private String refill(String in, int padding, int firstLinePadding, int refillWidth) { if (refillWidth <= 0) { return in; } // suffix is text *not* to refill. String suffix = null; int ulPos = in.indexOf(lineSep + "<ul>" + lineSep); if (ulPos != -1) { @SuppressWarnings( "index:argument.type.incompatible") String suffixTemp = in.substring(ulPos + lineSep.length()); suffix = suffixTemp; in = in.substring(0, ulPos); } String compressedSpaces = in.replaceAll("[ \n\r]+", " "); // In general, prefer {@code ...} to <code>...</code>. compressedSpaces = compressedSpaces.replaceAll("<code> ", "<code>"); if (compressedSpaces.startsWith(" ")) { compressedSpaces = compressedSpaces.substring(1); } String oneLine = StringUtils.repeat(" ", firstLinePadding) + compressedSpaces; StringJoiner multiLine = new StringJoiner(lineSep); while (oneLine.length() > refillWidth) { int breakLoc = oneLine.lastIndexOf(' ', refillWidth); if (breakLoc == -1) { break; } String firstPart = oneLine.substring(0, breakLoc); if (firstPart.trim().isEmpty()) { break; } multiLine.add(firstPart); oneLine = StringUtils.repeat(" ", padding) + oneLine.substring(breakLoc + 1); } multiLine.add(oneLine); if (suffix != null) { Scanner s = new Scanner(suffix); while (s.hasNextLine()) { multiLine.add(StringUtils.repeat(" ", padding) + s.nextLine()); } } return multiLine.toString(); } /** * Get the line of HTML describing one Option. * * @param oi the option to describe * @param padding the number of spaces to add at the begginning of the detail line (after the line * with the option itself) * @return HTML describing oi */ public String optionToHtml(Options.OptionInfo oi, int padding) { StringBuilder b = new StringBuilder(); Formatter f = new Formatter(b); if (oi.shortName != null) { f.format("<b>-%s</b> ", oi.shortName); } for (String a : oi.aliases) { f.format("<b>%s</b> ", a); } String prefix = getUseSingleDash() ? "-" : " f.format("<b>%s%s=</b><i>%s</i>", prefix, oi.longName, oi.typeName); if (oi.list != null) { b.append(" <code>[+]</code>"); } f.format(".%n "); f.format("%s", StringUtils.repeat(" ", padding)); String jdoc = ((oi.jdoc == null) ? "" : oi.jdoc); if (oi.noDocDefault || oi.defaultStr == null) { f.format("%s", jdoc); } else { String defaultStr = "default " + oi.defaultStr; // The default string must be HTML-escaped since it comes from a string // rather than a Javadoc comment. String suffix = ""; if (jdoc.endsWith("</p>")) { suffix = "</p>"; jdoc = jdoc.substring(0, jdoc.length() - suffix.length()); } f.format("%s [%s]%s", jdoc, StringEscapeUtils.escapeHtml4(defaultStr), suffix); } if (oi.baseType.isEnum()) { b.append(lineSep).append("<ul>").append(lineSep); assert oi.enumJdoc != null : "@AssumeAssertion(nullness): dependent: non-null if oi.baseType is an enum"; for (Map.Entry<String, String> entry : oi.enumJdoc.entrySet()) { b.append(" <li><b>").append(entry.getKey()).append("</b>"); if (entry.getValue().length() != 0) { b.append(" ").append(entry.getValue()); } // b.append("</li>"); b.append(lineSep); } b.append("</ul>").append(lineSep); } return b.toString(); } /** * Replace the @link tags and block @see tags in a Javadoc comment with HTML. * * <p>Currently, the output is non-hyperlinked HTML. This keeps most of the information in the * comment while still being presentable. Ideally, @link/@see tags would be converted to HTML * links that point to actual documentation. * * @param doc a Javadoc comment to convert to HTML * @return HTML version of doc */ public static String javadocToHtml(Doc doc) { StringBuilder b = new StringBuilder(); Tag[] tags = doc.inlineTags(); for (Tag tag : tags) { String kind = tag.kind(); String text = tag.text(); if (tag instanceof SeeTag) { b.append("<code>" + text.replace('#', '.') + "</code>"); } else { if (kind.equals("@code")) { b.append("<code>" + StringEscapeUtils.escapeHtml4(text) + "</code>"); } else { b.append(text); } } } SeeTag[] seetags = doc.seeTags(); if (seetags.length > 0) { b.append(" See: "); { StringJoiner bb = new StringJoiner(", "); for (SeeTag tag : seetags) { bb.add("<code>" + tag.text() + "</code>"); } b.append(bb); } b.append("."); } return b.toString(); } // Getters and Setters /** * Returns true if the output format is Javadoc, false if the output format is HTML. * * @return true if the output format is Javadoc, false if the output format is HTML */ public boolean getFormatJavadoc() { return formatJavadoc; } /** * Supply true to set the output format to Javadoc, false to set the output format to HTML. * * @param val true to set the output format to Javadoc, false to set the output format to HTML */ public void setFormatJavadoc(boolean val) { if (val && !formatJavadoc) { startDelim = "* " + startDelim; endDelim = "* " + endDelim; } else if (!val && formatJavadoc) { startDelim = StringUtils.removeStart("* ", startDelim); endDelim = StringUtils.removeStart("* ", endDelim); } this.formatJavadoc = val; } /** * Return true if using a single dash (as opposed to a double dash) for command-line options. * * @return whether to use a single dash (as opposed to a double dash) for command-line options */ public boolean getUseSingleDash() { return options.getUseSingleDash(); } /** * See {@link Options#setUseSingleDash(boolean)}. * * @param val whether to use a single dash (as opposed to a double dash) for command-line options */ public void setUseSingleDash(boolean val) { options.setUseSingleDash(true); } }
package de.faustedition; import de.faustedition.collation.CollationFinder; import de.faustedition.db.TransactionFilter; import de.faustedition.document.ArchiveRouter; import de.faustedition.document.DocumentRouter; import de.faustedition.genesis.GeneticGraphRouter; import de.faustedition.security.LdapSecurityStore; import de.faustedition.security.SecurityConstants; import de.faustedition.structure.StructureFinder; import de.faustedition.tei.GoddagFinder; import de.faustedition.template.TemplateFinder; import de.faustedition.text.TextFinder; import de.faustedition.xml.XMLFinder; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.Reference; import org.restlet.engine.application.Encoder; import org.restlet.representation.Representation; import org.restlet.resource.Directory; import org.restlet.resource.Finder; import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.restlet.routing.Filter; import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.security.Authenticator; import org.restlet.security.ChallengeAuthenticator; import org.restlet.security.Role; import org.restlet.security.RoleAuthorizer; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import java.util.List; import static org.restlet.data.ChallengeScheme.HTTP_BASIC; @Component public class FaustApplication extends Application implements InitializingBean { @Autowired private Environment environment; @Autowired private PlatformTransactionManager transactionManager; @Autowired private TemplateFinder templateFinder; @Autowired private GeneticGraphRouter geneticGraphRouter; @Autowired private ComboResourceFinder comboResourceFinder; @Autowired private ArchiveRouter archiveRouter; @Autowired private DocumentRouter documentRouter; @Autowired private GoddagFinder goddagFinder; @Autowired private TextFinder textFinder; @Autowired private XMLFinder xmlFinder; @Autowired private StructureFinder structureFinder; @Autowired private LdapSecurityStore ldapSecurityStore; @Autowired private CollationFinder collationFinder; private String staticResourcePath; @Override public void afterPropertiesSet() throws Exception { this.staticResourcePath = environment.getRequiredProperty("static.home"); } @Override public Restlet createInboundRoot() { final Router router = new Router(getContext()); router.setDefaultMatchingMode(Template.MODE_STARTS_WITH); router.attach("static/", new Directory(getContext().createChildContext(), "file://" + staticResourcePath + "/")); router.attach("project/", templateFinder); router.attach("archive/", secured(transactional(archiveRouter))); router.attach("collation/", secured(transactional(collationFinder))); router.attach("demo/", secured(transactional(templateFinder))); router.attach("genesis/", secured(transactional(geneticGraphRouter))); router.attach("document/", secured(transactional(documentRouter))); router.attach("goddag/", secured(transactional(goddagFinder))); router.attach("text/", secured(transactional(textFinder))); router.attach("structure/", secured(transactional(structureFinder))); router.attach("xml/", secured(xmlFinder)); router.attach("", EntryPageRedirectionResource.class, Template.MODE_EQUALS); router.attach("login", secured(new Finder(getContext().createChildContext(), EntryPageRedirectionResource.class))); router.attach("resources", comboResourceFinder); if (environment.acceptsProfiles("development", "test")) { final Filter dummyAuthenticator = new Filter() { @Override protected int beforeHandle(Request request, Response response) { final List<Role> roles = request.getClientInfo().getRoles(); roles.add(SecurityConstants.ADMIN_ROLE); roles.add(SecurityConstants.EDITOR_ROLE); roles.add(SecurityConstants.EXTERNAL_ROLE); return super.beforeHandle(request, response); } }; dummyAuthenticator.setNext(router); return dummyAuthenticator; } else { final Authenticator authenticator = new ChallengeAuthenticator(getContext().createChildContext(), true, HTTP_BASIC, "faustedition.net", ldapSecurityStore); authenticator.setEnroler(ldapSecurityStore); authenticator.setNext(router); final Encoder encoder = new Encoder(getContext()); encoder.setNext(authenticator); return encoder; } } private Restlet secured(Restlet resource) { final RoleAuthorizer authorizer = new RoleAuthorizer(); authorizer.getAuthorizedRoles().add(SecurityConstants.ADMIN_ROLE); authorizer.getAuthorizedRoles().add(SecurityConstants.EDITOR_ROLE); authorizer.getAuthorizedRoles().add(SecurityConstants.EXTERNAL_ROLE); authorizer.setNext(resource); return authorizer; } private Restlet transactional(Restlet resource) { return new TransactionFilter(getContext(), resource, transactionManager); } public static class EntryPageRedirectionResource extends ServerResource { @Override protected Representation doHandle() throws ResourceException { getResponse().redirectTemporary(new Reference(getReference(), "project/about")); return null; } } }
package ethanjones.cubes.world.generator; import ethanjones.cubes.block.Block; import ethanjones.cubes.side.Sided; import ethanjones.cubes.world.reference.AreaReference; import ethanjones.cubes.world.reference.BlockReference; import ethanjones.cubes.world.server.WorldServer; import ethanjones.cubes.world.storage.Area; public abstract class TerrainGenerator { public abstract void generate(Area area); public abstract void features(Area area, WorldServer world); public abstract BlockReference spawnPoint(WorldServer world); public static void set(Area area, Block block, int x, int y, int z) { int ref = Area.getRef(x, y, z); area.lock.writeLock(); area.setupArrays(); if (y > area.maxY) area.expand(y); area.blocks[ref] = Sided.getBlockManager().toInt(block); area.lock.writeUnlock(); } public static void set(WorldServer world, Block block, int x, int y, int z) { AreaReference areaReference = new AreaReference().setFromBlockCoordinates(x, z); world.lock.readLock(); Area area = world.getArea(areaReference, false); if (area == null) { world.lock.readUnlock(); throw new IllegalStateException(areaReference.toString()); } world.lock.readUnlock(); set(area, block, x - area.minBlockX, y, z - area.minBlockZ); //area.setBlock(block, x - area.minBlockX, y, z - area.minBlockZ); } }
package org.semtix.config; import org.apache.log4j.Logger; import org.semtix.shared.daten.enums.Uni; import java.io.File; import java.io.IOException; import java.util.Properties; public class SettingsExternal { public static int MAXTABS = 5; /** * Globale Debugging Variable : wenn true, dann werden Debugs in Konsole ausgegeben */ public static boolean DEBUG = false; public static String HOMEDIR = System.getProperty("user.home"); public static String TEMPLATE_PATH = null; public static String OUTPUT_PATH = null; public static String PDF_PATH = null; public static String HIBERNATE_CONF_XML = Settings.GLOBAL_CONF_DIR + "hibernate.cfg.xml"; /** * Dateinamen der Templates */ public static String TEMPLATE_ANTRAG_ABGELEHNT = ""; public static String TEMPLATE_ANTRAG_BAR = ""; public static String TEMPLATE_ANTRAG_KONTO = ""; public static String TEMPLATE_ANTRAG_BAR_KULANZ = ""; public static String TEMPLATE_ANTRAG_KONTO_KULANZ = ""; public static String TEMPLATE_ANTRAG_ABGELEHNT_KULANZ = ""; public static String TEMPLATE_AZA = ""; public static String TEMPLATE_AZA_HU = ""; public static String TEMPLATE_AZA_CHARITE = ""; public static String TEMPLATE_AZA_FINREF = ""; public static String DECKBLATT_DATEI = ""; public static String DECKBLATT_DATEI_KW = ""; public static String DECKBLATT_DATEI_HU = ""; public static String TEMPLATE_NACHFRAGE_DE = ""; public static String TEMPLATE_NACHFRAGE_EN = ""; public static String TEMPLATE_MAHNUNG_DE = ""; public static String TEMPLATE_MAHNUNG_EN = ""; /** * Pfad zu den LOG4-Properties, damit man sie auch nach /etc/ packen kann */ public static String LOG4JPATH = "/etc/semtixdb/log4j.properties"; /** * Layout-Modus mit Farben die die Panels unterscheiden */ public static boolean CHANGELAYOUTMODE = false; public static int ZUSAETZLICHE_SONSTIGE_HAERTEN = 4; static Logger logger = Logger.getLogger(SettingsExternal.class); public static String gettemplateAntragAbgelehnt() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_ANTRAG_ABGELEHNT; } public static String gettemplateAntragBar() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_ANTRAG_BAR; } public static String gettemplateAntragKonto() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_ANTRAG_KONTO; } public static String getTemplateAntragAbgelehntKulanz() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_ANTRAG_ABGELEHNT_KULANZ; } public static String getTemplateAntragBarKulanz() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_ANTRAG_BAR_KULANZ; } public static String getTemplateAntragKontoKulanz() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_ANTRAG_KONTO_KULANZ; } public static String gettemplateAza() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_AZA; } public static String gettemplateAzaHu() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_AZA_HU; } public static String gettemplateAzaCharite() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_AZA_CHARITE; } public static String gettemplateAzaFinref() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_AZA_FINREF; } public static String getdeckblattDatei() { StringBuilder path = new StringBuilder(SettingsExternal.TEMPLATE_PATH + File.separator); if (UniConf.aktuelleUni == Uni.HU) { path.append(DECKBLATT_DATEI_HU); } else { path.append((DECKBLATT_DATEI_KW)); } if (new File(path.toString()).exists()) { return path.toString(); } else { return TEMPLATE_PATH + File.separator + DECKBLATT_DATEI; } } public static String gettemplateNachfrageDe() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_NACHFRAGE_DE; } public static String gettemplateNachfrageEn() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_NACHFRAGE_EN; } public static String gettemplateMahnungDe() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_MAHNUNG_DE; } public static String gettemplateMahnungEn() { return SettingsExternal.TEMPLATE_PATH + "/" + TEMPLATE_MAHNUNG_EN; } public static void init(Properties einstellungen) { if(HOMEDIR.length()==0) { HOMEDIR = System.getProperty("user.dir"); } try { String ausgabepfad = einstellungen.getProperty("ausgabepfad").replaceAll("\\$HOME", HOMEDIR); if (ausgabepfad.length() > 0) { SettingsExternal.OUTPUT_PATH = ausgabepfad; } } catch (NullPointerException npe) { logger.warn("Ausgabepfad nicht in Properties angegeben."); } try { String ausgabepfad = einstellungen.getProperty("pdfpfad").replaceAll("\\$HOME", HOMEDIR); if (ausgabepfad.length() > 0) { SettingsExternal.PDF_PATH = ausgabepfad; } } catch (NullPointerException npe) { logger.warn("PDF-Ausgabepfad nicht in Properties angegeben."); } try { String vorlagenpfad = einstellungen.getProperty("vorlagenpfad").replaceAll("\\$HOME", HOMEDIR); if (vorlagenpfad.length() > 0) { SettingsExternal.TEMPLATE_PATH = vorlagenpfad; } } catch (NullPointerException npe) { logger.warn("Vorlagenpfad nicht in Properties angegeben."); } try { String hibernatepfad = einstellungen.getProperty("hibernatepfad"); if (hibernatepfad.length() > 0) { SettingsExternal.HIBERNATE_CONF_XML = hibernatepfad; } } catch (NullPointerException npe) { logger.warn("Hibernatepfad nicht in Properties angegeben."); } try { String log4jpfad = einstellungen.getProperty("log4jpfad"); if (log4jpfad.length() > 0) { LOG4JPATH = log4jpfad; } } catch (NullPointerException npe) { logger.warn("LOG4J-Pfad nicht in Properties angegeben."); } try { if (einstellungen.getProperty("colors").length() > 0) CHANGELAYOUTMODE = Boolean.parseBoolean(einstellungen.getProperty("colors")); } catch (Exception e) { logger.warn("Feld colors sollte ein boolean sein. Also z.B. 'true' oder 'false'"); } try { if (einstellungen.getProperty("max.tabs").length() > 0) MAXTABS = Integer.parseInt(einstellungen.getProperty("max.tabs")); } catch (Exception e) { logger.warn("Feld max.tabs sollte eine Ganzzahl sein. Also z.B. 7"); } try { if (einstellungen.getProperty("debug").length() > 0) DEBUG = Boolean.parseBoolean(einstellungen.getProperty("debug")); } catch (Exception e) { logger.warn("Feld debug sollte ein boolean sein. Also z.B. 'true' oder 'false'"); } try { if (einstellungen.getProperty("add.sonstige.haerten").length() > 0) ZUSAETZLICHE_SONSTIGE_HAERTEN = Integer.parseInt(einstellungen.getProperty("add.sonstige.haerten")); } catch (Exception e) { logger.warn("Feld add.sonstige.haerten sollte eine Ganzzahl zwischen 0 und 7 sein."); } if (null == OUTPUT_PATH) logger.warn("Bitte überprüfen Sie ob 'ausgabepfad=<pfad>' in semtixconf.properties angegeben ist."); if (null == PDF_PATH) logger.warn("Bitte überprüfen Sie ob 'pdfpfad=<pfad>' in semtixconf.properties angegeben ist."); if (null == TEMPLATE_PATH) logger.warn("Bitte überprüfen Sie ob 'vorlagenpfad=<pfad>' in semtixconf.properties angegeben ist."); if (null == HIBERNATE_CONF_XML) logger.error("Bitte überprüfen Sie ob 'hibernatepfad=<pfad>' in semtixconf.properties angegeben ist. Hibernate ist für diese Anwendung zwingend notwendig."); try { if (einstellungen.getProperty("vorlage.bescheid.ablehnung").length() > 0) TEMPLATE_ANTRAG_ABGELEHNT = einstellungen.getProperty("vorlage.bescheid.ablehnung"); if (einstellungen.getProperty("vorlage.bescheid.bar").length() > 0) TEMPLATE_ANTRAG_BAR = einstellungen.getProperty("vorlage.bescheid.bar"); if (einstellungen.getProperty("vorlage.bescheid.konto").length() > 0) TEMPLATE_ANTRAG_KONTO = einstellungen.getProperty("vorlage.bescheid.konto"); if (einstellungen.getProperty("vorlage.auszahlungsanordnung").length() > 0) TEMPLATE_AZA = einstellungen.getProperty("vorlage.auszahlungsanordnung"); if (einstellungen.getProperty("vorlage.auszahlungsanordnung.hu").length() > 0) TEMPLATE_AZA_HU = einstellungen.getProperty("vorlage.auszahlungsanordnung.hu"); if (einstellungen.getProperty("vorlage.auszahlungsanordnung.charite").length() > 0) TEMPLATE_AZA_CHARITE = einstellungen.getProperty("vorlage.auszahlungsanordnung.charite"); if (einstellungen.getProperty("vorlage.auszahlungsanordnung.finref").length() > 0) TEMPLATE_AZA_FINREF = einstellungen.getProperty("vorlage.auszahlungsanordnung.finref"); if (einstellungen.getProperty("deckblatt.auszahlungsdatei").length() > 0) { DECKBLATT_DATEI = einstellungen.getProperty("deckblatt.auszahlungsdatei"); } if (einstellungen.getProperty("deckblatt.auszahlungsdatei.hu").length() > 0) { DECKBLATT_DATEI_HU = einstellungen.getProperty("deckblatt.auszahlungsdatei.hu"); } if (einstellungen.getProperty("deckblatt.auszahlungsdatei.kw").length() > 0) { DECKBLATT_DATEI_KW = einstellungen.getProperty("deckblatt.auszahlungsdatei.kw"); } if (einstellungen.getProperty("vorlage.nachfage.EN").length() > 0) { TEMPLATE_NACHFRAGE_EN = einstellungen.getProperty("vorlage.nachfage.EN"); } if (einstellungen.getProperty("vorlage.nachfage.DE").length() > 0) { TEMPLATE_NACHFRAGE_DE = einstellungen.getProperty("vorlage.nachfage.DE");; } if (einstellungen.getProperty("vorlage.mahnung.EN").length() > 0) { TEMPLATE_MAHNUNG_EN = einstellungen.getProperty("vorlage.mahnung.EN"); } if (einstellungen.getProperty("vorlage.mahnung.DE").length() > 0) { TEMPLATE_MAHNUNG_DE = einstellungen.getProperty("vorlage.mahnung.DE"); } } catch (NullPointerException npe) { logger.warn("Eine oder mehrere Vorlagen sind nicht angegeben. Programm verwendet in diesen Fällen die voreingestellten Dateinamen."); } } public static void einstellungenSpeichern() throws IOException { Properties einstellungen = new Properties(); if (!(null == OUTPUT_PATH)) einstellungen.setProperty("ausgabepfad", OUTPUT_PATH); else System.out.println("Bitte Varable 'ausgabepfad' manuell in " + Settings.DEFAULT_PROPERTIES_GLOBAL + " setzen."); if (!(null == PDF_PATH)) einstellungen.setProperty("ausgabepfad", PDF_PATH); else System.out.println("Bitte Varable 'pdfpfad' manuell in " + Settings.DEFAULT_PROPERTIES_GLOBAL + " setzen."); if (!(null == TEMPLATE_PATH)) einstellungen.setProperty("vorlagenpfad", TEMPLATE_PATH); else System.out.println("Bitte Varable 'vorlagenpfad' manuell in " + Settings.DEFAULT_PROPERTIES_GLOBAL + " setzen."); einstellungen.setProperty("hibernatepfad", HIBERNATE_CONF_XML); einstellungen.setProperty("log4jpfad", LOG4JPATH); einstellungen.setProperty("vorlage.bescheid.ablehnung", TEMPLATE_ANTRAG_ABGELEHNT); einstellungen.setProperty("vorlage.bescheid.bar", TEMPLATE_ANTRAG_BAR); einstellungen.setProperty("vorlage.bescheid.konto", TEMPLATE_ANTRAG_KONTO); einstellungen.setProperty("vorlage.auszahlungsanordnung", TEMPLATE_AZA); einstellungen.setProperty("vorlage.auszahlungsanordnung.hu", TEMPLATE_AZA_HU); einstellungen.setProperty("vorlage.auszahlungsanordnung.finref", TEMPLATE_AZA_FINREF); einstellungen.setProperty("deckblatt.auszahlungsdatei", DECKBLATT_DATEI); einstellungen.setProperty("deckblatt.auszahlungsdatei.hu", DECKBLATT_DATEI_HU); einstellungen.setProperty("deckblatt.auszahlungsdatei.kw", DECKBLATT_DATEI_KW); einstellungen.setProperty("vorlage.nachfage.DE", TEMPLATE_NACHFRAGE_DE); einstellungen.setProperty("vorlage.nachfage.EN", TEMPLATE_NACHFRAGE_EN); einstellungen.setProperty("vorlage.mahnung.DE", TEMPLATE_MAHNUNG_DE); einstellungen.setProperty("vorlage.mahnung.EN", TEMPLATE_MAHNUNG_EN); einstellungen.setProperty("colors", "" + CHANGELAYOUTMODE); einstellungen.setProperty("debug", "" + DEBUG); einstellungen.setProperty("max.tabs", "" + MAXTABS); einstellungen.setProperty("log4jpfad", LOG4JPATH); einstellungen.setProperty("add.sonstige.haerten", "" + ZUSAETZLICHE_SONSTIGE_HAERTEN); PropertiesManagement.saveProperties(einstellungen, Settings.DEFAULT_PROPERTIES_GLOBAL, "Einstellungen Semtix"); } }
package crawl_index; import java.nio.file.Files; import java.nio.file.Paths; import java.io.*; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.StringField; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.util.Version; public class indexerTfidf { private final File sourceDirectory; private final File indexDirectory; private static String fieldName; public indexerTfidf() { this.sourceDirectory = new File("C:/tika/path"); this.indexDirectory = new File("C:/index/nn"); fieldName = "contents1"; } // Method for Creating Index // public void index() throws CorruptIndexException, LockObtainFailedException, IOException { Directory dir = FSDirectory.open(indexDirectory); Analyzer analyzer = new StandardAnalyzer(StandardAnalyzer.STOP_WORDS_SET); // using stop words IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_2, analyzer); if (indexDirectory.exists()) { iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE); } else { // Add new documents to an existing index // iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND); } IndexWriter writer = new IndexWriter(dir, iwc); for (File f : sourceDirectory.listFiles()) { Document doc = new Document(); FieldType fieldType = new FieldType(); fieldType.setIndexed(true); fieldType.setIndexOptions(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); fieldType.setStored(true); fieldType.setStoreTermVectors(true); fieldType.setTokenized(true); Field contentField = new Field(fieldName, getAllText(f), fieldType); // added path to index for output try { Field pathField = new StringField("path", f.toString(), Field.Store.YES); doc.add(pathField); }catch (Exception e) { } doc.add(contentField); writer.addDocument(doc); } writer.close(); } // Method to get all Index // public String getAllText(File f) throws FileNotFoundException, IOException { String textFileContent = ""; for (String line : Files.readAllLines(Paths.get(f.getAbsolutePath()))) { textFileContent += line; } return textFileContent; } }
package org.spongepowered.api.util.ban; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.service.ban.BanService; import org.spongepowered.api.text.Text; import org.spongepowered.api.util.ResettableBuilder; import java.net.InetAddress; import java.time.Instant; import java.util.Optional; import javax.annotation.Nullable; /** * Represents a ban made on an object. */ public interface Ban { /** * Creates a new Builder. * * @return A new ban builder */ static Builder builder() { return Sponge.getRegistry().createBuilder(Builder.class); } /** * Creates an indefinite ban on a profile. * * @param profile The profile * @return The created ban */ static Ban of(GameProfile profile) { return builder().type(BanTypes.PROFILE).profile(profile).build(); } /** * Creates an indefinite ban with a reason on a profile. * * @param profile The profile * @param reason The reason * @return The created ban */ static Ban of(GameProfile profile, Text reason) { return builder().type(BanTypes.PROFILE).profile(profile).reason(reason).build(); } /** * Gets the type of this ban. * * @return The ban type */ BanType getType(); /** * Get the reason for the ban, if available. * * @return The reason specified for the ban, if available */ Optional<Text> getReason(); /** * Gets the creation date of the ban. * * <p>Note that this {@link Instant} has no effect on whether or not a ban is * active. Any ban for which {@link BanService#hasBan(Ban)} returns * <code>true</code> will be used (when checking if a player can join, * for example), regardless of its creation date.</p> * * @return Creation date of the ban */ Instant getCreationDate(); /** * Gets the source that created this ban, if available * * <p>Depending on the implementation, the returned {@link Text} * may represent a {@link CommandSource}. {@link #getBanCommandSource()} can be * used to attempt to convert the source to a {@link CommandSource}.</p> * * @return the source of this ban, if available */ Optional<Text> getBanSource(); /** * Gets the source that created this ban in {@link CommandSource} form, if available * * <p>Depending on the implementation, it may not be possible to determine * the {@link CommandSource} responsible for this ban. Because of this, * it is reccomended to check {@link #getBanSource()} if this method * returns {@link Optional#empty()}.</p> * * @return The banning source or {@link Optional#empty()} */ Optional<CommandSource> getBanCommandSource(); /** * Gets the expiration date of this ban, if available. * * @return Expiration time of the ban or {@link Optional#empty()} */ Optional<Instant> getExpirationDate(); /** * Gets whether this ban is indefinitely long, e.g. has no expiration date. * * @return True if this ban has no expiration date, otherwise false */ default boolean isIndefinite() { return !this.getExpirationDate().isPresent(); } /** * Represents a ban made on a {@link GameProfile}. */ interface Profile extends Ban { /** * Gets the {@link GameProfile} this ban applies to. * * @return The {@link GameProfile} */ GameProfile getProfile(); } /** * Represents a ban made on an IP. */ interface Ip extends Ban { /** * Gets the address this ban applies to. * * @return The address */ InetAddress getAddress(); } /** * Represents a builder that creates bans. */ interface Builder extends ResettableBuilder<Ban, Builder> { /** * Sets the profile to be banned. * * <p>This can only be done if the {@link BanType} has been set to {@link BanTypes#PROFILE}.</p> * * @param profile The profile * @return This builder */ Builder profile(GameProfile profile); /** * Sets the IP address to be banned. * * <p>This can only be done if the {@link BanType} has been set to {@link BanTypes#IP}.</p> * * @param address The IP address * @return This builder */ Builder address(InetAddress address); /** * Sets the type of the ban. * * @param type The type to be set * @return This builder */ Builder type(BanType type); /** * Sets the reason for the ban. * * <p>If the specified reason is <code>null</code>, or not provided, * then the reason will be be available on the created ban.</p> * * @param reason The reason * @return This builder */ Builder reason(@Nullable Text reason); /** * Sets the date that the ban starts. * * @param instant The start date * @return This builder */ Builder startDate(Instant instant); /** * Sets the expiration date of the ban, or removes it. * * @param instant The expiration date, or null in order to remove it * @return This builder */ Builder expirationDate(@Nullable Instant instant); /** * Sets the source of the ban, or removes it if {@code null} is passed * in. * * @param source The source of the ban, or {@code null} * @return This builder */ Builder source(@Nullable CommandSource source); /** * Sets the source of the ban as a {@link Text}, or removes it if * {@code null} is passed in. * * @param source The source of the ban, or {@code null} * @return This builder */ Builder source(@Nullable Text source); /** * Creates a new Ban from this builder. * * @return A new Ban */ Ban build(); } }
package bisq.core.dao.state.period; import bisq.core.dao.DaoSetupService; import bisq.core.dao.state.BsqStateListener; import bisq.core.dao.state.BsqStateService; import bisq.core.dao.state.GenesisTxInfo; import bisq.core.dao.state.blockchain.Block; import bisq.core.dao.state.governance.Param; import com.google.inject.Inject; import com.google.common.collect.ImmutableList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; @Slf4j public class CycleService implements BsqStateListener, DaoSetupService { private final BsqStateService bsqStateService; private final int genesisBlockHeight; // Constructor @Inject public CycleService(BsqStateService bsqStateService, GenesisTxInfo genesisTxInfo) { this.bsqStateService = bsqStateService; this.genesisBlockHeight = genesisTxInfo.getGenesisBlockHeight(); } // DaoSetupService @Override public void addListeners() { bsqStateService.addBsqStateListener(this); } @Override public void start() { bsqStateService.getCycles().add(getFirstCycle()); } // BsqStateListener @Override public void onNewBlockHeight(int blockHeight) { if (blockHeight != genesisBlockHeight) maybeCreateNewCycle(blockHeight, bsqStateService.getCycles()) .ifPresent(bsqStateService.getCycles()::add); } @Override public void onParseTxsComplete(Block block) { } @Override public void onParseBlockChainComplete() { } // API private Optional<Cycle> maybeCreateNewCycle(int blockHeight, LinkedList<Cycle> cycles) { // We want to set the correct phase and cycle before we start parsing a new block. // For Genesis block we did it already in the start method. // We copy over the phases from the current block as we get the phase only set in // applyParamToPhasesInCycle if there was a changeEvent. // The isFirstBlockInCycle methods returns from the previous cycle the first block as we have not // applied the new cycle yet. But the first block of the old cycle will always be the same as the // first block of the new cycle. Cycle cycle = null; if (blockHeight != genesisBlockHeight && isFirstBlockAfterPreviousCycle(blockHeight, cycles)) { // We have the not update bsqStateService.getCurrentCycle() so we grab here the previousCycle final Cycle previousCycle = cycles.getLast(); // We create the new cycle as clone of the previous cycle and only if there have been change events we use // the new values from the change event. cycle = createNewCycle(blockHeight, previousCycle); } return Optional.ofNullable(cycle); } private Cycle getFirstCycle() { // We want to have the initial data set up before the genesis tx gets parsed so we do it here in the constructor // as onAllServicesInitialized might get called after the parser has started. // We add the default values from the Param enum to our StateChangeEvent list. List<DaoPhase> daoPhasesWithDefaultDuration = Arrays.stream(DaoPhase.Phase.values()) .map(this::getPhaseWithDefaultDuration) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); return new Cycle(genesisBlockHeight, ImmutableList.copyOf(daoPhasesWithDefaultDuration)); } public int getCycleIndex(Cycle cycle) { return (cycle.getHeightOfFirstBlock() - genesisBlockHeight) / cycle.getDuration(); } public boolean isTxInCycle(Cycle cycle, String txId) { return bsqStateService.getTx(txId).filter(tx -> isBlockHeightInCycle(tx.getBlockHeight(), cycle)).isPresent(); } private boolean isBlockHeightInCycle(int blockHeight, Cycle cycle) { return blockHeight >= cycle.getHeightOfFirstBlock() && blockHeight <= cycle.getHeightOfLastBlock(); } // Private private Cycle createNewCycle(int blockHeight, Cycle previousCycle) { List<DaoPhase> daoPhaseList = previousCycle.getDaoPhaseList().stream() .map(daoPhase -> { DaoPhase.Phase phase = daoPhase.getPhase(); try { Param param = Param.valueOf("PHASE_" + phase.name()); long value = bsqStateService.getParamValue(param, blockHeight); return new DaoPhase(phase, (int) value); } catch (Throwable ignore) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); return new Cycle(blockHeight, ImmutableList.copyOf(daoPhaseList)); } private boolean isFirstBlockAfterPreviousCycle(int height, LinkedList<Cycle> cycles) { final int previousBlockHeight = height - 1; final Optional<Cycle> previousCycle = getCycle(previousBlockHeight, cycles); return previousCycle .filter(cycle -> cycle.getHeightOfLastBlock() + 1 == height) .isPresent(); } private Optional<DaoPhase> getPhaseWithDefaultDuration(DaoPhase.Phase phase) { return Arrays.stream(Param.values()) .filter(param -> isParamMatchingPhase(param, phase)) .map(param -> new DaoPhase(phase, (int) param.getDefaultValue())) .findAny(); // We will always have a default value defined } private boolean isParamMatchingPhase(Param param, DaoPhase.Phase phase) { return param.name().contains("PHASE_") && param.name().replace("PHASE_", "").equals(phase.name()); } private Optional<Cycle> getCycle(int height, LinkedList<Cycle> cycles) { return cycles.stream() .filter(cycle -> cycle.getHeightOfFirstBlock() <= height) .filter(cycle -> cycle.getHeightOfLastBlock() >= height) .findAny(); } }
package org.swingeasy; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.text.JTextComponent; import javax.swing.tree.TreePath; import ca.odell.glazedlists.matchers.Matcher; /** * @author Jurgen */ public class ETreeSearchComponent<T> extends JComponent { /** serialVersionUID */ private static final long serialVersionUID = 5196244125968828897L; protected final ETree<T> eTree; protected JTextComponent input; public ETreeSearchComponent(ETree<T> eTree) { this.eTree = eTree; this.init(); } protected void init() { this.setLayout(new BorderLayout()); this.input = new JTextField(); this.input.setBorder(null); this.input.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { ETreeSearchComponent.this.search(); } } }); this.add(this.input, BorderLayout.CENTER); JButton commit = new EIconButton(new Dimension(18, 18), Resources.getImageResource("find.png"));//$NON-NLS-1$ commit.setActionCommand("search");//$NON-NLS-1$ commit.setToolTipText(Messages.getString("ETree.SearchComponent.search"));//$NON-NLS-1$ commit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ETreeSearchComponent.this.search(); } }); this.add(commit, BorderLayout.EAST); JLabel label = new JLabel(Messages.getString("ETree.SearchComponent.search") + ": "); //$NON-NLS-1$ //$NON-NLS-2$ this.add(label, BorderLayout.WEST); } protected void search() { String text = this.input.getText(); if (text.length() == 0) { return; } TreePath current; try { current = this.eTree.getSelectionPath(); if (current == null) { throw new NullPointerException(); } } catch (Exception ex) { current = new TreePath(this.eTree.getModel().getRoot()); } final Pattern pattern = Pattern.compile(text, Pattern.CASE_INSENSITIVE); ETreeI<T> stsi = this.eTree.stsi(); TreePath nextMatch; try { nextMatch = stsi.getNextMatch(current, new Matcher<T>() { @Override public boolean matches(T item) { return pattern.matcher(String.valueOf(item)).find(); } }); } catch (IllegalArgumentException ex) { current = new TreePath(this.eTree.getModel().getRoot()); nextMatch = stsi.getNextMatch(current, new Matcher<T>() { @Override public boolean matches(T item) { return pattern.matcher(String.valueOf(item)).find(); } }); } if (nextMatch != null) { stsi.setSelectionPath(nextMatch); } else { String message = Messages.getString("ETree.SearchComponent.nomatch");//$NON-NLS-1$ String title = Messages.getString("ETree.SearchComponent.searchmatch");//$NON-NLS-1$ JOptionPane.showMessageDialog(this, message, title, JOptionPane.INFORMATION_MESSAGE); } } }
package org.webedded.cors; import java.io.IOException; import java.net.HttpURLConnection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Handler for exceptions and other controls extensions. * * @author Voiski<alannunesv@gmail.com> */ public interface CorsProxyHandler { /** * Customize parameters for request of service. * * @param connection proxy connection * @param request current request */ void handleRequestProperty(HttpURLConnection connection, HttpServletRequest request) throws IOException; /** * Customize parameters for head of response * * @param request current request * @param response current response */ void handleResponseHeader(HttpServletRequest request,HttpServletResponse response) throws IOException; /** * Control the response by code response from original service. * * @param request current request * @param response current response * @param proxyUrl url of original service * @param responseCode response code of original service request. * @return true if this can continue with normal response, false otherwise. */ boolean handleResponseCode(HttpServletRequest request,HttpServletResponse response, String proxyUrl, int responseCode) throws IOException; /** * Set servlet instance to permite interactions with some values like maps. * * @param corsProxyServlet current servlet */ void setServlet(CorsProxyServlet corsProxyServlet); }
// Nexus Core - a framework for developing distributed applications package com.threerings.nexus.client; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import react.Function; import react.RFuture; import react.RPromise; import react.Slot; import com.threerings.nexus.distrib.Address; import com.threerings.nexus.distrib.NexusException; import com.threerings.nexus.distrib.NexusObject; import com.threerings.nexus.net.Connection; import static com.threerings.nexus.util.Log.log; /** * Manages connections to Nexus servers. Provides access to distributed objects and services. */ public abstract class NexusClient { /** * Creates a subscriber, see {@link Subscriber} for details. */ public <T extends NexusObject> Subscriber<T> subscriber () { return new SubImpl<T>(); } /** * Creates and returns a new subscriber. If the supplied {@code subscriber} is non-null, it * will be unsubscribed. This is essentially a helper method to simplify a common pattern where * an existing subscription, if it exists, needs to be unsubscribed, and a new subscription * created, all in one fell swoop. */ public <T extends NexusObject> Subscriber<T> subscriber (Subscriber<?> subscriber) { if (subscriber != null) subscriber.unsubscribe(); return this.<T>subscriber(); } /** * Closes all active connections. */ public void closeAll () { for (RPromise<Connection> conn : new ArrayList<RPromise<Connection>>(_conns.values())) { conn.onSuccess(new Slot<Connection>() { public void onEmit (Connection conn) { conn.close(); } }); } } protected abstract void connect (String host, RPromise<Connection> promise); // TODO: should we disconnect immediately when clearing last subscription from a given // connection, or should we periodically poll our open connections and disconnect any with no // active subscriptions (this would allow a little leeway, so that a usage pattern wherein one // unsubscribed from their last object on a given server and then immediately subscribed to a // new one, did not cause needless disconnect and reconnect) protected void disconnect (String serverHost) { // TODO } /** * Establishes a connection with the supplied host (if one does not already exist), and makes * it available to the caller via a future. Ensures thread-safety in the process. */ protected synchronized RFuture<Connection> connection (final String host) { RPromise<Connection> conn = _conns.get(host); if (conn == null) { _conns.put(host, conn = RPromise.create()); final Slot<Throwable> remover = new Slot<Throwable>() { public void onEmit (Throwable error) { _conns.remove(host); if (error == null) log.info("Connection to " + host + " closed."); else log.info("Connection to " + host + " failed.", "error", error); } }; conn.onFailure(remover).onSuccess(new Slot<Connection>() { // listen for connection close and remove our connection then public void onEmit (Connection conn) { conn.onClose.connect(remover); } }); log.info("Connecting to " + host); connect(host, conn); } return conn; } protected class SubImpl<T extends NexusObject> implements Subscriber<T> { @Override public RFuture<T> subscribe (final Address<? extends T> addr) { if (_id >= 0) throw new IllegalStateException("Subscriber already used"); _id = 0; return connection(addr.host).flatMap(new Function<Connection,RFuture<T>>() { public RFuture<T> apply (Connection conn) { if (!_alive) return canceled(); return (_conn = conn).subscribe(addr).flatMap(new Function<T,RFuture<T>>() { public RFuture<T> apply (T obj) { _id = obj.getId(); // things are normal; complete with this result and we're done if (_alive) return RFuture.success(obj); // otherwise we unsubscribed before the object arrived, handle that unsubscribe(); return canceled(); } }); } }); } @Override public RFuture<T> apply (Address<? extends T> addr) { return _alive ? subscribe(addr) : canceled(); } @Override public void unsubscribe () { // if we've already unsubscribed, then we're done if (_id == -1) return; // if we have not yet received our object, we have to wait for the object to arrive // before we can turn around and unsubscribe from it else if (_id == 0) _alive = false; // otherwise we can send the unsubscribe request else { _conn.unsubscribe(_id); _id = -1; } } protected RFuture<T> canceled () { return RFuture.failure(new NexusException("Subscription canceled")); } protected Connection _conn; protected boolean _alive = true; protected int _id = -2; } /** A mapping from hostname to connection instance for all pending and active connections. */ protected Map<String, RPromise<Connection>> _conns = new HashMap<String, RPromise<Connection>>(); }
package org.webedded.cors; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.text.MessageFormat; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet to proxy access where normally is need of CORS where has issues about * legacy browser without full implementation, like control of session. * * @author Voiski<alannunesv@gmail.com> */ public class CorsProxyServlet extends HttpServlet { private static final long serialVersionUID = -3053743543344180905L; private static final String HEADER_FIELD_HOST = "Host"; private static final String HEADER_FIELD_CONTENT_TYPE = "Content-Type"; private static final String HEADER_FIELD_SET_COOKIE = "Set-Cookie"; private static final String HEADER_FIELD_SET_COOKIE_VALUE_DELIMITER = ";"; private static final String HEADER_FIELD_COOKIE_JSESSIONID = "JSESSIONID"; private static final String PREFIX_FILE_PROTOCOL = "file: private static final String PREFIX_CLASSPATH_PROTOCOL = "classpath: // Init params from web.xml public static final String INIT_CONFIG_PATH = "org.webedded.cors.conf_path"; public static final String INIT_HANDLER_CLASS = "org.webedded.cors.handler_class"; // Params from resource config private static final String INIT_CONFIG_KEYSTORETYPE = "javax.net.ssl.keyStoreType"; private static final String INIT_CONFIG_TRUSTSTORETYPE = "javax.net.ssl.trustStoreType"; private static final String INIT_CONFIG_KEYSTORE = "javax.net.ssl.keyStore"; private static final String INIT_CONFIG_TRUSTSTORE = "javax.net.ssl.trustStore"; private static final String INIT_CONFIG_DEBUG = "javax.net.debug"; private static final String INIT_CONFIG_KEYSTOREPASSWORD = "javax.net.ssl.keyStorePassword"; private static final String INIT_CONFIG_TRUSTSTOREPASSWORD = "javax.net.ssl.trustStorePassword"; private static final String HEADER_X_PROXY_LOCATION = "X-Proxy-Location"; private static final String HEADER_X_REST_METHOD = "X-REST-Method"; private static final String HEADER_TRANSFER_ENCODING = "Transfer-Encoding"; public static final int DEFAULT_BUFFER_SIZE = 1024; private static final Map<String, ContextService> contextServicesMap = new HashMap<String, ContextService>(); private static final Map<String, String> contextResoucesMap = new HashMap<String, String>(); private static CorsProxyHandler handler; @Override public void init(final ServletConfig config) throws ServletException { super.init(config); // Get configuretion file for cors proxy final Properties externalConfiguration = new Properties(); try { String confPath = config.getInitParameter(INIT_CONFIG_PATH); if (confPath == null) { confPath = "${jboss.server.home.dir}/conf/cors-proxy-conf.properties"; } if(confPath.startsWith(PREFIX_CLASSPATH_PROTOCOL)){ externalConfiguration .load(getClass().getResourceAsStream( confPath.substring(PREFIX_CLASSPATH_PROTOCOL .length()))); }else if(new File(this.simpleElTransform(confPath)).exists()){ externalConfiguration.load(new FileInputStream(this .simpleElTransform(confPath))); } } catch (final IOException e) { Logger.getLogger(this.getClass().getName()) .warning( "Error loading CORS-Proxy configuration: " + e.getMessage()); } // Add servlet int parameters to config map, this will permite config // the same values inside the war but in external configuration will // override them. for (@SuppressWarnings("unchecked") final Enumeration<String> enumeration = config.getInitParameterNames(); enumeration.hasMoreElements();) { final String key = enumeration.nextElement(); if(externalConfiguration.getProperty(key)!=null){ externalConfiguration.setProperty(key, config.getInitParameter(key)); } } initHandler(config); // Configure access to SSL setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_KEYSTORETYPE); setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_KEYSTORE); setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_KEYSTOREPASSWORD); setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_TRUSTSTORETYPE); setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_TRUSTSTORE); setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_TRUSTSTOREPASSWORD); setSystemPropertieIfExist(externalConfiguration, INIT_CONFIG_DEBUG); // Configure contexts of services/resources to concat operations for (final Enumeration<Object> keys = externalConfiguration.keys(); keys.hasMoreElements();) { final String singleKey = (String) keys.nextElement(); if (singleKey.startsWith(ContextService.INIT_CONFIG_SUFIX_SERVICES)) { final String context = singleKey.substring(ContextService.INIT_CONFIG_SUFIX_SERVICES.length()); final String url = this.simpleElTransform(externalConfiguration.getProperty(singleKey)); contextServicesMap.put(context, ContextService.reuse(contextServicesMap.get(context),context, url)); } else if (singleKey.startsWith(ContextService.INIT_CONFIG_SUFIX_FROM)) { final String context = singleKey.substring(ContextService.INIT_CONFIG_SUFIX_FROM.length()); final String urlFrom = this.simpleElTransform(externalConfiguration.getProperty( singleKey )); final String urlTo = this.simpleElTransform(externalConfiguration.getProperty( MessageFormat.format(ContextService.INIT_CONFIG_TO_MASK, context) )); ContextService.getFromMap(contextServicesMap,context.substring(0,context.indexOf('.'))).putResource(urlFrom, urlTo); } else if (singleKey.startsWith(ContextService.INIT_CONFIG_COPY_HEADERS)){ final String condition = this.simpleElTransform(externalConfiguration.getProperty(singleKey)); if("true".equalsIgnoreCase(condition) || "1".equalsIgnoreCase(condition)){ final String context = singleKey.substring(ContextService.INIT_CONFIG_COPY_HEADERS.length()); ContextService.getFromMap(contextServicesMap,context).enableCopyHeaders(); } } } } /** * Configure handler, if not exist custom class use a single implementation. */ private void initHandler(final ServletConfig config) throws ServletException { if(config.getInitParameter(INIT_HANDLER_CLASS)!=null){ try { @SuppressWarnings("rawtypes") final Class clazz = this.getClass().getClassLoader().loadClass(config.getInitParameter(INIT_HANDLER_CLASS)); handler = (CorsProxyHandler) clazz.newInstance(); } catch (final ClassNotFoundException e) { Logger.getLogger(CorsProxyServlet.class.getName()).log( Level.SEVERE, null, e); throw new ServletException("Error in configuration of handler for CORS Proxy!",e); } catch (InstantiationException e) { Logger.getLogger(CorsProxyServlet.class.getName()).log( Level.SEVERE, null, e); throw new ServletException("Error in configuration of handler for CORS Proxy!",e); } catch (IllegalAccessException e) { Logger.getLogger(CorsProxyServlet.class.getName()).log( Level.SEVERE, null, e); throw new ServletException("Error in configuration of handler for CORS Proxy!",e); } }else{ handler = new CorsProxyHandler(){ public void handleRequestProperty(final HttpURLConnection connection, HttpServletRequest request) { } public void handleResponseHeader(final HttpServletRequest request, HttpServletResponse response) { } public void initServlet(final CorsProxyServlet corsProxyServlet) { } public boolean handleResponseCode(final HttpServletRequest request, final HttpServletResponse response, final String proxyUrl, final int responseCode) { return true; } }; } handler.initServlet(this); } @Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String requestUrl = request.getQueryString() == null ? request .getRequestURL().toString() : MessageFormat.format("{0}?{1}", request.getRequestURL().toString(), request.getQueryString()); final String proxyUrl = this.buildUrl(requestUrl, request.getServletPath()); if (proxyUrl == null) { throw new ServletException("No " + HEADER_X_PROXY_LOCATION + " header present."); } try { if (proxyUrl.startsWith(PREFIX_FILE_PROTOCOL)) { reponseFromFile(request, response, proxyUrl); } else if (proxyUrl.startsWith(PREFIX_CLASSPATH_PROTOCOL)) { reponseFromClasspath(request, response, proxyUrl); } else { reponseFromConnection(request, response, proxyUrl); } } catch (final IOException ex) { Logger.getLogger(CorsProxyServlet.class.getName()).log( Level.SEVERE, null, ex); throw new ServletException(ex); } } /** * Create the response for overrided resource ignoring proxy to origin * service */ private void reponseFromFile(final HttpServletRequest request, final HttpServletResponse response, final String proxyUrl) throws IOException { response.setHeader(HEADER_FIELD_CONTENT_TYPE, request.getHeader(HEADER_FIELD_CONTENT_TYPE)); handler.handleResponseHeader(request, response); this.copyStream( new FileInputStream(proxyUrl.substring(PREFIX_FILE_PROTOCOL .length())), response.getOutputStream()); } /** * Create the response for overrided resource inside classpath ignoring * proxy to origin service */ private void reponseFromClasspath(final HttpServletRequest request, final HttpServletResponse response, final String proxyUrl) throws IOException { response.setHeader(HEADER_FIELD_CONTENT_TYPE, request.getHeader(HEADER_FIELD_CONTENT_TYPE)); handler.handleResponseHeader(request, response); this.copyStream( getClass().getResourceAsStream( proxyUrl.substring(PREFIX_CLASSPATH_PROTOCOL.length())), response.getOutputStream()); } /** * Create the response for proxy connection of a service */ public void reponseFromConnection(final HttpServletRequest request, final HttpServletResponse response, final String proxyUrl) throws IOException { final String serviceContext = this.getUrlContext(request .getRequestURL().toString(), request.getServletPath()); final StringBuffer bufferStream = new StringBuffer(""); HttpURLConnection connection = createConnection(request, response, proxyUrl, bufferStream); response.setStatus(connection.getResponseCode()); if(handler.handleResponseCode(request, response, proxyUrl, connection.getResponseCode())){ // Pass back headers final Map<String, List<String>> responseHeaders = connection .getHeaderFields(); final ContextService contextService = contextServicesMap.get(serviceContext); for (final Entry<String, List<String>> entry : responseHeaders .entrySet()) { if (entry.getKey() != null && !HEADER_TRANSFER_ENCODING.equalsIgnoreCase(entry.getKey())) { if (entry.getKey().equalsIgnoreCase( HEADER_FIELD_SET_COOKIE)) { String cookieValue = this.concatComma(entry.getValue()); cookieValue = cookieValue.substring(cookieValue .indexOf("=") + 1, cookieValue .indexOf(HEADER_FIELD_SET_COOKIE_VALUE_DELIMITER)); request.getSession().setAttribute( HEADER_FIELD_COOKIE_JSESSIONID + "-" + serviceContext, cookieValue); }else if (contextService.isCopyHeaders() || entry.getKey().equalsIgnoreCase(HEADER_FIELD_CONTENT_TYPE)) { response.setHeader(entry.getKey(), this.concatComma(entry.getValue())); } } } handler.handleResponseHeader(request, response); try{ this.copyStream(connection.getInputStream(), response.getOutputStream()); }catch(final IOException ioe){ if(ioe.getMessage().contains("Server returned HTTP")){ this.copyStream(connection.getErrorStream(), response.getOutputStream()); }else{ throw ioe; } } } } /** * Create the connection with parsed header and content body of initial * request. */ private HttpURLConnection createConnection( final HttpServletRequest request, final HttpServletResponse response, final String proxyUrl, final StringBuffer bufferStream) throws IOException, MalformedURLException, ProtocolException { final HttpURLConnection connection = (HttpURLConnection) new URL( proxyUrl).openConnection(); final String serviceContext = this.getUrlContext(request .getRequestURL().toString(), request.getServletPath()); String method = request.getHeader(proxyUrl); if (method == null) { method = request.getMethod(); } final boolean doOutput = method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT"); if (proxyUrl.toLowerCase().startsWith("https")) { ((HttpsURLConnection) connection) .setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory .getDefault()); } connection.setDoOutput(doOutput); connection.setRequestMethod(method.toUpperCase()); final String lastSessionID = (String) request.getSession() .getAttribute( HEADER_FIELD_COOKIE_JSESSIONID + "-" + serviceContext); // Duplicate headers for (@SuppressWarnings("rawtypes") final Enumeration enu = request.getHeaderNames(); enu.hasMoreElements();) { final String headerName = (String) enu.nextElement(); if (headerName.equals(HEADER_X_REST_METHOD) || headerName.equals(HEADER_X_PROXY_LOCATION)) { continue; } final String headerValue = request.getHeader(headerName); if (HEADER_FIELD_HOST.equalsIgnoreCase(headerName)) { connection.setRequestProperty(HEADER_FIELD_HOST, connection .getURL().getHost()); } else if ("Cookie".equalsIgnoreCase(headerName) && lastSessionID != null) { final String[] cookies = headerValue .split(HEADER_FIELD_SET_COOKIE_VALUE_DELIMITER); final StringBuilder cookiesForHeaderValue = new StringBuilder( headerValue.length()); cookiesForHeaderValue.append(HEADER_FIELD_COOKIE_JSESSIONID) .append("=").append(lastSessionID) .append(HEADER_FIELD_SET_COOKIE_VALUE_DELIMITER); for (final String cookie : cookies) { if (!cookie.startsWith(HEADER_FIELD_COOKIE_JSESSIONID)) { cookiesForHeaderValue.append(cookie).append( HEADER_FIELD_SET_COOKIE_VALUE_DELIMITER); } } connection.setRequestProperty(headerName, cookiesForHeaderValue.toString()); } else { connection.setRequestProperty(headerName, headerValue); } } handler.handleRequestProperty(connection, request); if (doOutput) { this.copyStream(request.getInputStream(), connection.getOutputStream()); } return connection; } /** * @return url from context service or path to resource if has override * configured */ private String buildUrl(final String requestUrl, final String servletPath) { final String urlContent = requestUrl.split(servletPath)[1]; final String serviceContext = urlContent.substring(1,urlContent.indexOf('/', 1)); return contextServicesMap.get(serviceContext).getOriginUrl(urlContent); } /** * @return context of map for parser of url, this isnt the context of url. */ private String getUrlContext(final String requestUrl, final String servletPath) { final String urlContent = requestUrl.split(servletPath)[1]; final String serviceContext = urlContent.substring(1, urlContent.indexOf('/', 1)); return serviceContext; } /** * Copies the data from an InputStream object to an OutputStream object. * * @param sourceStream * The input stream to be read. * @param destinationStream * The output stream to be written to. * @exception IOException * from java.io calls. */ private void copyStream(final InputStream sourceStream, final OutputStream destinationStream) throws IOException { int bytesRead = 0; final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; while (bytesRead >= 0) { bytesRead = sourceStream.read(buffer, 0, buffer.length); if (bytesRead > 0) { destinationStream.write(buffer, 0, bytesRead); } } } private String simpleElTransform(final String elValue) { final String result; if (elValue==null || !elValue.contains("${")) { result = elValue; } else { final StringBuilder resultBuilder = new StringBuilder( elValue.length()); final String[] parties = elValue.split("[\\$}]"); for (final String single : parties) { if (single.length() > 0 && single.charAt(0) == '{') { if (System.getProperty(single.substring(1)) != null) { resultBuilder.append(System.getProperty(single .substring(1))); } } else { resultBuilder.append(single); } } result = resultBuilder.toString(); } return result; } private String concatComma(final List<String> strings) { final Iterator<String> it = strings.iterator(); StringBuilder sb = new StringBuilder(it.next()); while (it.hasNext()) { sb = sb.append(",").append(it.next()); } return sb.toString(); } private void setSystemPropertieIfExist(final Properties externalConfiguration, final String key) { final String value=externalConfiguration.getProperty(key); if(value!=null){ System.getProperties().setProperty(key, this.simpleElTransform(value)); } } /** * You can use this to add new services with handler if you dont want to use * external config. * * @return map with services */ public Map<String, ContextService> getContextServicesMap() { return contextServicesMap; } /** * You can use this to add new resources with handler if you dont want to * use external config. * * @return map with resources */ public Map<String, String> getContextResoucesMap() { return contextResoucesMap; } }
package pl.warsjawa.java8.people; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.util.Collections; import java.util.List; public class PersonDao { public List<Person> loadPeopleDatabase() { try (BufferedReader bufferedReader = open("/people.csv")) { return Collections.emptyList(); // return bufferedReader.lines(). } catch (IOException e) { throw new RuntimeException(e); } } private BufferedReader open(String fileName) { return new BufferedReader( new InputStreamReader( getClass().getResourceAsStream(fileName), StandardCharsets.UTF_8)); } private Person parseLine(String line) { final String[] columns = line.split(","); return new Person( columns[0], Sex.valueOf(columns[1]), Integer.parseInt(columns[3]), Integer.parseInt(columns[2]), LocalDate.of( Integer.parseInt(columns[6]), Integer.parseInt(columns[5]), Integer.parseInt(columns[4]) ) ); } }
package org.bitcoinj.kits; import com.google.common.collect.ImmutableList; import org.bitcoinj.core.Context; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Utils; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChainGroup; import org.bitcoinj.wallet.Wallet; import java.io.File; import java.security.SecureRandom; import static org.bitcoinj.wallet.DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS; public class EvolutionWalletAppKit extends WalletAppKit { @Deprecated public static ImmutableList<ChildNumber> EVOLUTION_ACCOUNT_PATH = ImmutableList.of(new ChildNumber(5, true), ChildNumber.FIVE_HARDENED, ChildNumber.ZERO_HARDENED); public EvolutionWalletAppKit(Context context, File directory, String filePrefix, boolean liteMode) { super(context, directory, filePrefix, liteMode); } public EvolutionWalletAppKit(NetworkParameters params, File directory, String filePrefix, boolean liteMode) { super(params, directory, filePrefix, liteMode); } @Override protected Wallet createWallet() { KeyChainGroup kcg; if (restoreFromSeed != null) kcg = new KeyChainGroup(params, restoreFromSeed, EVOLUTION_ACCOUNT_PATH); else { kcg = new KeyChainGroup(params, new DeterministicSeed(new SecureRandom(), DEFAULT_SEED_ENTROPY_BITS,""), EVOLUTION_ACCOUNT_PATH); } if (walletFactory != null) { return walletFactory.create(params, kcg); } else { return new Wallet(params, kcg); // default } } }
package ru.r2cloud.jradio.source; import java.io.IOException; import ru.r2cloud.jradio.Context; import ru.r2cloud.jradio.FloatInput; import ru.r2cloud.jradio.FloatValueSource; import ru.r2cloud.jradio.util.NumericallyControlledOscillator; public class SigSource implements FloatInput { private final Waveform waveform; private final float[] complex = new float[2]; private final Context context; private NumericallyControlledOscillator nco; private boolean real = true; public SigSource(Waveform waveform, long sampleRate, final float frequency, double amplitude) { this(waveform, sampleRate, () -> frequency, amplitude); } public SigSource(Waveform waveform, final long sampleRate, final FloatValueSource frequency, double amplitude) { this.waveform = waveform; nco = new NumericallyControlledOscillator(() -> frequency.getValue() / sampleRate, amplitude); context = new Context(); context.setSampleRate(sampleRate); context.setSampleSizeInBits(32); switch (waveform) { case COMPLEX: context.setChannels(2); break; case COSINE: case SINE: context.setChannels(1); break; default: throw new IllegalArgumentException("unsupported waveform: " + waveform); } } @Override public float readFloat() throws IOException { float result; switch (waveform) { case COMPLEX: if (real) { nco.sincos(complex); result = complex[0]; } else { result = complex[1]; } real = !real; break; case COSINE: result = nco.cos(); break; case SINE: result = nco.sin(); break; default: throw new IllegalArgumentException("unsupported waveform: " + waveform); } return result; } @Override public void close() throws IOException { // do nothing } @Override public Context getContext() { return context; } }
package ru.salauyou.util.misc; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; public class StatsBuilder<V extends Comparable<? super V>> implements Collector<V, StatsBuilder<V>, StatsBuilder<V>> { final Queue<V> values = new ConcurrentLinkedQueue<>(); final AtomicInteger items = new AtomicInteger(); final int toSkip; public StatsBuilder() { this(0); } /** * Creates a new StatsBuilder that will ignore * N first items */ public StatsBuilder(int skipFirst) { this.toSkip = skipFirst; } public StatsBuilder<V> put(V v) { int c = items.incrementAndGet(); if (toSkip != 0 && c <= toSkip) return this; values.add(v); return this; } public StatsBuilder<V> putAll(Iterable<? extends V> from) { for (V v : from) put(v); return this; } public StatsBuilder<V> putAll(StatsBuilder<? extends V> from) { for (V v : from.values) put(v); return this; } public List<? super V> getPercentiles(double[] percentiles) throws IllegalArgumentException { List<V> vs = new ArrayList<>(values); if (vs.size() == 0) return Collections.emptyList(); Collections.sort(vs); List<V> result = new ArrayList<>(percentiles.length); for (int i = 0; i < percentiles.length; i++) { if (percentiles[i] < 0) throw new IllegalArgumentException("Percentile cannot be less than 0"); int idx = (int) Math.round(vs.size() * percentiles[i] / 100d) - 1; idx = Math.min(idx, vs.size() - 1); idx = Math.max(idx, 0); result.add(vs.get(idx)); } return result; } public String percentilesToString(double[] percentiles) throws IllegalArgumentException { StringBuilder sb = new StringBuilder(); List<? super V> percentileValues = this.getPercentiles(percentiles); for (int i = 0; i < percentiles.length; i++) { sb.append(percentiles[i]) .append("%\t") .append(percentileValues.get(i)); if (i == percentiles.length - 1) return sb.toString(); sb.append('\n'); } return ""; } /** * Number of counted items (skipped items not included) */ public int getCount() { return values.size(); } /** * Number of all items accepted by <tt>put()/putAll()</tt>, * including skipped items */ public int totalCount() { return items.get(); } @Override public Supplier<StatsBuilder<V>> supplier() { return StatsBuilder::new; } @Override public BiConsumer<StatsBuilder<V>, V> accumulator() { return StatsBuilder::put; } @Override public BinaryOperator<StatsBuilder<V>> combiner() { return StatsBuilder::putAll; } @Override public Function<StatsBuilder<V>, StatsBuilder<V>> finisher() { return Function.identity(); } static final Set<Collector.Characteristics> CH = Collections.unmodifiableSet(EnumSet.of( Collector.Characteristics.UNORDERED, Collector.Characteristics.IDENTITY_FINISH, Collector.Characteristics.CONCURRENT)); @Override public Set<Collector.Characteristics> characteristics() { return CH; } }
package edu.cs4460.msd.visual.maps; import java.awt.Color; import processing.core.PApplet; import ch.randelshofer.tree.NodeInfo; import ch.randelshofer.tree.circlemap.CirclemapNode; import ch.randelshofer.tree.circlemap.CirclemapTree; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MBTilesMapProvider; import de.fhpotsdam.unfolding.utils.MapUtils; import de.fhpotsdam.unfolding.utils.ScreenPosition; import edu.cs4460.msd.backend.genre.GenreFilter; import edu.cs4460.msd.backend.maps_works.ContinentData; import edu.cs4460.msd.backend.utilities.PathHandler; import edu.cs4460.msd.backend.visual_abstract.AbstractMap; import edu.cs4460.msd.visual.circles.CirclemapDraw; import edu.cs4460.msd.visual.controls.ToolTip; public class GenreLocationMap extends AbstractMap { private PApplet parent; private int x, y, width, height; private CirclemapTree[] models; private CirclemapDraw[] cmDraws; private NodeInfo[] infos; private boolean[] drawContinent = {false, false, false, false, false, false}; private CirclemapNode hoverNode; private int hoverIndex; private boolean isToolTipVisible = true; private ToolTip tooltip; public GenreLocationMap(PApplet p, int x, int y, int width, int height, CirclemapTree[] models) { this.parent = p; this.x = x; this.y = y; this.width = width; this.height = height; PathHandler ph = new PathHandler(); String mbTilesConnectionString = "jdbc:sqlite:" + ph.getPathToResource("blankLight-1-3.mbtiles"); map = new UnfoldingMap(parent, "detail", x, y, width, height, true, false, new MBTilesMapProvider(mbTilesConnectionString)); map.setPanningRestriction(getMapCenter(), 0); map.setZoomRange(1, 1); MapUtils.createDefaultEventDispatcher(parent, map); this.models = models; this.cmDraws = new CirclemapDraw[6]; this.infos = new NodeInfo[6]; for (int i = 0; i < 6; i++) { this.cmDraws[i] = new CirclemapDraw(this.models[i]); this.cmDraws[i].setRadius(40); ContinentData cd = new ContinentData(); Location loc = cd.getContinentCenter(ContinentData.getContinents()[i]); ScreenPosition pos = map.getScreenPosition(loc); this.cmDraws[i].setCX(pos.x); this.cmDraws[i].setCY(pos.y); this.infos[i] = this.models[i].getInfo(); } } public void draw() { map.draw(); for(int i = 0; i < 6; i++) { if (drawContinent[i]) { cmDraws[i].drawTree(parent); } } if (hoverNode != null) { if(infos[hoverIndex].getWeight(hoverNode.getDataNodePath()) > 0) { cmDraws[hoverIndex].drawNodeBounds(parent, hoverNode, Color.red); if (this.isToolTipVisible && hoverNode != cmDraws[hoverIndex].getRoot()) { //tooltip.draw(); } } } } public void mouseMoved(int mx, int my) { for (int i = 0; i < 6; i++) { if (drawContinent[i]) { hoverNode = cmDraws[i].getNodeAt(mx, my); if (hoverNode != null) { hoverIndex = i; break; } } } } public void setDrawContinent(int index, boolean bool) { drawContinent[index] = bool; } private Location getMapCenter() { return getMapLocation(x + width / 2,y + height / 2); } public Location getMapLocation(int mouseX, int mouseY) { return map.getLocation(mouseX, mouseY); } @Override public void updateFilter(GenreFilter filter) { // TODO Auto-generated method stub } }
package seedu.taskitty.model.task; import java.time.DateTimeException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import seedu.taskitty.commons.exceptions.IllegalValueException; import seedu.taskitty.commons.util.DateUtil; /** * Represents a Task's date in the task manager. * Guarantees: immutable; is valid as declared in {@link #isValidDate(String)} */ public class TaskDate { public static final String MESSAGE_DATE_CONSTRAINTS = "Task dates should be in the format dd/mm/yyyy or ddmmyyyy or dd monthname yyyy"; public static final String MESSAGE_DATE_INVALID = "Task date provided is invalid!"; public static final String MESSAGE_DATE_MISSING = "Task date must be provided"; public static final String DATE_FORMAT_STRING = "MM/dd/yyyy"; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT_STRING); //format: mm/dd/yyyy private static final String DATE_VALIDATION_REGEX = "[\\p{Digit}]{1,2}/[\\p{Digit}]{1,2}/[\\p{Digit}]{4}"; public final LocalDate date; public TaskDate(String date) throws IllegalValueException { if (date == null) { throw new IllegalValueException(MESSAGE_DATE_MISSING); } date = date.trim(); if (!isValidDate(date)) { throw new IllegalValueException(MESSAGE_DATE_CONSTRAINTS); } this.date = LocalDate.parse(date, DATE_FORMATTER); } /** * Returns true if a given string is a valid person name. */ public static boolean isValidDate(String test) { return test.matches(DATE_VALIDATION_REGEX); } @Override public String toString() { return date.format(DATE_FORMATTER); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof TaskDate // instanceof handles nulls && this.date.equals(((TaskDate) other).date)); // state check } @Override public int hashCode() { return date.hashCode(); } public LocalDate getDate() { return date; } }
/* * $Log: JdbcException.java,v $ * Revision 1.5 2006-12-12 09:58:41 europe\L190409 * fix version string * * Revision 1.4 2006/12/12 09:57:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restore jdbc package * * Revision 1.2 2004/03/26 10:43:07 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.1 2004/03/24 13:28:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * initial version * */ package nl.nn.adapterframework.jdbc; import nl.nn.adapterframework.core.IbisException; /** * Wrapper for JDBC related exceptions. * * @version Id * @author Gerrit van Brakel * @since 4.1 */ public class JdbcException extends IbisException { public static final String version = "$RCSfile: JdbcException.java,v $ $Revision: 1.5 $ $Date: 2006-12-12 09:58:41 $"; public JdbcException() { super(); } public JdbcException(String arg1) { super(arg1); } public JdbcException(String arg1, Throwable arg2) { super(arg1, arg2); } public JdbcException(Throwable arg1) { super(arg1); } }
/* * $Log: Trigger.java,v $ * Revision 1.5 2008-08-27 16:18:07 europe\L190409 * fixed period handling * * Revision 1.4 2008/08/07 11:31:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * rework * * Revision 1.3 2008/07/24 12:34:01 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * rework * * Revision 1.2 2008/07/17 16:17:19 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * rework * * Revision 1.1 2008/07/14 17:21:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * first version of flexible monitoring * */ package nl.nn.adapterframework.monitoring; import java.util.Date; import java.util.LinkedList; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.util.DateUtils; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.XmlBuilder; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; /** * @author Gerrit van Brakel * @since 4.9 * @version Id */ public class Trigger { protected Logger log = LogUtil.getLogger(this); private Monitor owner; private SeverityEnum severity; private boolean alarm; private String eventCode; private String source; private int threshold=0; private int period=0; private LinkedList eventDts=null; public void configure() throws ConfigurationException { if (StringUtils.isEmpty(eventCode)) { log.warn("trigger of Monitor ["+owner.getName()+"] should have eventCode specified"); } if (StringUtils.isNotEmpty(eventCode)) { try { getOwner().registerEventNotificationListener(this,eventCode,source); } catch (MonitorException e) { throw new ConfigurationException(e); } } if (threshold>0) { if (eventDts==null) { eventDts = new LinkedList(); } } else { eventDts=null; } } public void evaluateEvent(EventThrowing source, String eventCode) throws MonitorException { Date now = new Date(); if (getThreshold()>0) { cleanUpEvents(now); eventDts.add(now); if (eventDts.size()>=getThreshold()) { getOwner().changeState(now, alarm, getSeverityEnum(), source, eventCode, null); } } else { getOwner().changeState(now, alarm, getSeverityEnum(), source, eventCode, null); } } public void notificationOfReverseTrigger(EventThrowing source) { if (eventDts!=null) { eventDts.clear(); } } protected void cleanUpEvents(Date now) { while(eventDts.size()>0) { Date firstDate = (Date)eventDts.getFirst(); if ((now.getTime()-firstDate.getTime())>getPeriod()*1000) { eventDts.removeFirst(); if (log.isDebugEnabled()) log.debug("removed element dated ["+DateUtils.format(firstDate)+"]"); } else { break; } } } public void toXml(XmlBuilder monitor) { XmlBuilder trigger=new XmlBuilder(isAlarm()?"alarm":"clearing"); monitor.addSubElement(trigger); trigger.addAttribute("eventCode",getEventCode()); if (StringUtils.isNotEmpty(getSource())) { trigger.addAttribute("source",getSource()); } if (getSeverity()!=null) { trigger.addAttribute("severity",getSeverity()); } if (getThreshold()>0) { trigger.addAttribute("threshold",getThreshold()); } if (getPeriod()>0) { trigger.addAttribute("period",getPeriod()); } } public void setOwner(Monitor monitor) { owner = monitor; } public Monitor getOwner() { return owner; } public String toString() { return ToStringBuilder.reflectionToString(this); } public void setAlarm(boolean b) { alarm = b; } public boolean isAlarm() { return alarm; } public String getType() { if (isAlarm()) { return "Alarm"; } else { return "Clearing"; } } public void setType(String type) { if (type.equalsIgnoreCase("Alarm")) { setAlarm(true); } if (type.equalsIgnoreCase("Clearing")) { setAlarm(false); } } public void setEventCode(String string) { eventCode = string; } public String getEventCode() { return eventCode; } public void setSeverity(String severity) { setSeverityEnum((SeverityEnum)SeverityEnum.getEnumMap().get(severity)); } public void setSeverityEnum(SeverityEnum enum) { severity = enum; } public SeverityEnum getSeverityEnum() { return severity; } public String getSeverity() { return severity==null?null:severity.getName(); } public void setThreshold(int i) { threshold = i; } public int getThreshold() { return threshold; } public void setPeriod(int i) { period = i; } public int getPeriod() { return period; } public void setSource(String source) { this.source = source; } public String getSource() { return source; } }
package net.mueller_martin.turirun.gameobjects; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.Color; public class GameObject { public Vector2 position; public Vector2 size; public Rectangle bounds; public int id = 0; private ShapeRenderer shapeRenderer; public GameObject (float x, float y, float width, float height) { this.position = new Vector2(x, y); this.size = new Vector2(width, height); this.bounds = new Rectangle(x - width / 2, y - height / 2, width, height); this.shapeRenderer = new ShapeRenderer(); } public void update() { } public void draw(SpriteBatch batch) { batch.begin(); shapeRenderer.begin(ShapeType.Filled); shapeRenderer.setColor(Color.BLUE); shapeRenderer.rect(this.position.x, this.position.y, this.size.x, this.size.y); shapeRenderer.end(); batch.end(); } }
package com.namelessdev.mpdroid; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.exception.MPDServerException; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.View; import android.widget.ArrayAdapter; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.namelessdev.mpdroid.fragments.NowPlayingFragment; import com.namelessdev.mpdroid.fragments.PlaylistFragment; import com.namelessdev.mpdroid.fragments.PlaylistFragmentCompat; import com.namelessdev.mpdroid.library.LibraryTabActivity; import com.namelessdev.mpdroid.tools.Tools; public class MainMenuActivity extends SherlockFragmentActivity implements OnNavigationListener { public static final int PLAYLIST = 1; public static final int ARTISTS = 2; public static final int SETTINGS = 5; public static final int STREAM = 6; public static final int LIBRARY = 7; public static final int CONNECT = 8; /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private int backPressExitCount; private Handler exitCounterReset; @SuppressLint("NewApi") @TargetApi(11) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); exitCounterReset = new Handler(); if (android.os.Build.VERSION.SDK_INT >= 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Create the adapter that will return a fragment for each of the three primary sections // of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(true); ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(this, R.layout.sherlock_spinner_item); actionBarAdapter.add(getString(R.string.nowPlaying)); actionBarAdapter.add(getString(R.string.playQueue)); if(Build.VERSION.SDK_INT >= 14) { //Bug on ICS with sherlock's layout actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } else { actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); } actionBar.setListNavigationCallbacks(actionBarAdapter, this); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); if (android.os.Build.VERSION.SDK_INT >= 9) mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER); // When swiping between different sections, select the corresponding tab. // We can also use ActionBar.Tab#select() to do this if we have a reference to the // Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); } @Override public void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplicationContext(); app.setActivity(this); } @Override public void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.unsetActivity(this); } /** * Called when Back button is pressed, displays message to user indicating the if back button is pressed again the application will exit. We keep a count of how many time back * button is pressed within 5 seconds. If the count is greater than 1 then call system.exit(0) * * Starts a post delay handler to reset the back press count to zero after 5 seconds * * @return None */ @Override public void onBackPressed() { if (backPressExitCount < 1) { Tools.notifyUser(String.format(getResources().getString(R.string.backpressToQuit)), this); backPressExitCount += 1; exitCounterReset.postDelayed(new Runnable() { @Override public void run() { backPressExitCount = 0; } }, 5000); } else { /* * Nasty force quit, should shutdown everything nicely but there just too many async tasks maybe I'll correctly implement app.terminateApplication(); */ System.exit(0); } return; } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { mViewPager.setCurrentItem(itemPosition); return true; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary * sections of the app. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Fragment fragment = null; switch (i) { case 0: fragment = new NowPlayingFragment(); break; case 1: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fragment = new PlaylistFragment(); } else { fragment = new PlaylistFragmentCompat(); } break; } return fragment; } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.nowPlaying); case 1: return getString(R.string.playQueue); } return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.mpd_mainmenu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { //Reminder : never disable buttons that are shown as actionbar actions here super.onPrepareOptionsMenu(menu); MPDApplication app = (MPDApplication) this.getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; if (!mpd.isConnected()) { if (menu.findItem(CONNECT) == null) { menu.add(0, CONNECT, 0, R.string.connect); } } else { if (menu.findItem(CONNECT) != null) { menu.removeItem(CONNECT); } } setMenuChecked(menu.findItem(R.id.GMM_Stream), app.getApplicationState().streamingMode); final MPDStatus mpdStatus = app.getApplicationState().currentMpdStatus; if (mpdStatus != null) { setMenuChecked(menu.findItem(R.id.GMM_Single), mpdStatus.isSingle()); setMenuChecked(menu.findItem(R.id.GMM_Consume), mpdStatus.isConsume()); } return true; } private void setMenuChecked(MenuItem item, boolean checked) { // Set the icon to a checkbox so 2.x users also get one item.setChecked(checked); item.setIcon(checked ? R.drawable.btn_check_buttonless_on : R.drawable.btn_check_buttonless_off); } private void openLibrary() { final Intent i = new Intent(this, LibraryTabActivity.class); startActivity(i); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i = null; final MPDApplication app = (MPDApplication) this.getApplication(); final MPD mpd = app.oMPDAsyncHelper.oMPD; // Handle item selection switch (item.getItemId()) { case R.id.menu_search: this.onSearchRequested(); return true; case R.id.GMM_LibTab: openLibrary(); return true; case R.id.GMM_Settings: i = new Intent(this, SettingsActivity.class); startActivityForResult(i, SETTINGS); return true; case R.id.GMM_Outputs: i = new Intent(this, SettingsActivity.class); i.putExtra(SettingsActivity.OPEN_OUTPUT, true); startActivityForResult(i, SETTINGS); return true; case CONNECT: ((MPDApplication) this.getApplication()).connect(); return true; case R.id.GMM_Stream: if (((MPDApplication) this.getApplication()).getApplicationState().streamingMode) { // yeah, yeah getApplication for that may be ugly but i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.DIE"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = false; // Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show(); } else { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.START_STREAMING"); this.startService(i); ((MPDApplication) this.getApplication()).getApplicationState().streamingMode = true; // Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show(); } return true; case R.id.GMM_bonjour: startActivity(new Intent(this, ServerListActivity.class)); return true; case R.id.GMM_Consume: try { mpd.setConsume(!mpd.getStatus().isConsume()); } catch (MPDServerException e) { } return true; case R.id.GMM_Single: try { mpd.setSingle(!mpd.getStatus().isSingle()); } catch (MPDServerException e) { } return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.next(); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.previous(); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); return true; } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { // For onKeyLongPress to work event.startTracking(); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { final MPDApplication app = (MPDApplication) getApplicationContext(); switch (event.getKeyCode()) { case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_DOWN: if (event.isTracking() && !event.isCanceled() && !app.getApplicationState().streamingMode) { new Thread(new Runnable() { @Override public void run() { try { app.oMPDAsyncHelper.oMPD.adjustVolume(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP ? NowPlayingFragment.VOLUME_STEP : -NowPlayingFragment.VOLUME_STEP); } catch (MPDServerException e) { e.printStackTrace(); } } }).start(); } return true; } return super.onKeyUp(keyCode, event); } }
package com.namelessdev.mpdroid; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import org.a0z.mpd.MPD; import org.a0z.mpd.MPDServerException; import org.a0z.mpd.MPDStatus; import org.a0z.mpd.Music; import org.a0z.mpd.event.MPDConnectionStateChangedEvent; import org.a0z.mpd.event.MPDPlaylistChangedEvent; import org.a0z.mpd.event.MPDRandomChangedEvent; import org.a0z.mpd.event.MPDRepeatChangedEvent; import org.a0z.mpd.event.MPDStateChangedEvent; import org.a0z.mpd.event.MPDTrackChangedEvent; import org.a0z.mpd.event.MPDTrackPositionChangedEvent; import org.a0z.mpd.event.MPDUpdateStateChangedEvent; import org.a0z.mpd.event.MPDVolumeChangedEvent; import org.a0z.mpd.event.StatusChangeListener; import org.a0z.mpd.event.TrackPositionListener; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; import com.namelessdev.mpdroid.CoverAsyncHelper.CoverDownloadListener; public class MainMenuActivity extends Activity implements StatusChangeListener, TrackPositionListener, CoverDownloadListener, OnSharedPreferenceChangeListener { private Logger myLogger = Logger.global; public static final String PREFS_NAME = "mpdroid.properties"; public static final int PLAYLIST = 1; public static final int ARTISTS = 2; public static final int SETTINGS = 5; public static final int STREAM = 6; public static final int LIBRARY = 7; public static final int CONNECT = 8; private TextView artistNameText; private TextView songNameText; private TextView albumNameText; public static final int ALBUMS = 4; public static final int FILES = 3; private SeekBar progressBarVolume = null; private SeekBar progressBarTrack = null; private TextView trackTime = null; private CoverAsyncHelper oCoverAsyncHelper = null; long lastSongTime = 0; long lastElapsedTime = 0; private ImageSwitcher coverSwitcher; private ProgressBar coverSwitcherProgress; private static final int VOLUME_STEP = 5; private static final int TRACK_STEP = 10; private static final int ANIMATION_DURATION_MSEC = 1000; private StreamingService streamingServiceBound; private boolean isStreamServiceBound; private ButtonEventHandler buttonEventHandler; @SuppressWarnings("unused") private boolean streamingMode; private boolean connected; private Timer volTimer = new Timer(); private TimerTask volTimerTask = null; // Used for detecting sideways flings private GestureDetector gestureDetector; View.OnTouchListener gestureListener; private boolean enableLastFM; private boolean newUI; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SETTINGS: break; default: break; } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE); myLogger.log(Level.INFO, "onCreate"); // registerReceiver(, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION) ); registerReceiver(MPDConnectionHandler.getInstance(), new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); gestureDetector = new GestureDetector(new MyGestureDetector(this)); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; // oMPDAsyncHelper.addConnectionListener(MPDConnectionHandler.getInstance(this)); init(); } @Override protected void onRestart() { super.onRestart(); myLogger.log(Level.INFO, "onRestart"); } @Override protected void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplication(); app.oMPDAsyncHelper.addStatusChangeListener(this); app.oMPDAsyncHelper.addTrackPositionListener(this); app.setActivity(this); myLogger.log(Level.INFO, "onStart"); } @Override protected void onResume() { super.onResume(); myLogger.log(Level.INFO, "onResume"); // Annoyingly this seams to be run when the app starts the first time to. // Just to make sure that we do actually get an update. try { updateTrackInfo(); } catch (Exception e) { e.printStackTrace(); } try { MPDApplication app = (MPDApplication) getApplication(); progressBarVolume.setProgress(app.oMPDAsyncHelper.oMPD.getStatus().getVolume()); } catch (MPDServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); int wifistate = wifi.getWifiState(); * if(wifistate!=wifi.WIFI_STATE_ENABLED && wifistate!=wifi.WIFI_STATE_ENABLING) { setTitle("No WIFI"); return; } * while(wifistate!=wifi.WIFI_STATE_ENABLED) setTitle("Waiting for WIFI"); */ } private void init() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); settings.registerOnSharedPreferenceChangeListener(this); enableLastFM = settings.getBoolean("enableLastFM", true); newUI = settings.getBoolean("newUI", false); if (newUI) { setContentView(R.layout.main); } else { setContentView(R.layout.main_old); } streamingMode = ((MPDApplication) getApplication()).isStreamingMode(); connected = ((MPDApplication) getApplication()).oMPDAsyncHelper.oMPD.isConnected(); artistNameText = (TextView) findViewById(R.id.artistName); albumNameText = (TextView) findViewById(R.id.albumName); songNameText = (TextView) findViewById(R.id.songName); progressBarTrack = (SeekBar) findViewById(R.id.progress_track); progressBarVolume = (SeekBar) findViewById(R.id.progress_volume); trackTime = (TextView) findViewById(R.id.trackTime); Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); fadeIn.setDuration(ANIMATION_DURATION_MSEC); Animation fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); fadeOut.setDuration(ANIMATION_DURATION_MSEC); coverSwitcher = (ImageSwitcher) findViewById(R.id.albumCover); coverSwitcher.setFactory(new ViewFactory() { public View makeView() { ImageView i = new ImageView(MainMenuActivity.this); i.setBackgroundColor(0x00FF0000); i.setScaleType(ImageView.ScaleType.FIT_CENTER); // i.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return i; } }); coverSwitcher.setInAnimation(fadeIn); coverSwitcher.setOutAnimation(fadeOut); coverSwitcherProgress = (ProgressBar) findViewById(R.id.albumCoverProgress); coverSwitcherProgress.setIndeterminate(true); coverSwitcherProgress.setVisibility(ProgressBar.INVISIBLE); oCoverAsyncHelper = new CoverAsyncHelper(); oCoverAsyncHelper.addCoverDownloadListener(this); buttonEventHandler = new ButtonEventHandler(); ImageButton button = (ImageButton) findViewById(R.id.next); button.setOnClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.prev); button.setOnClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.back); button.setOnClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.playpause); button.setOnClickListener(buttonEventHandler); button.setOnLongClickListener(buttonEventHandler); button = (ImageButton) findViewById(R.id.forward); button.setOnClickListener(buttonEventHandler); progressBarVolume.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub System.out.println("Vol2:" + progressBarVolume.getProgress()); } }); progressBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } public void onStartTrackingTouch(SeekBar seekBar) { volTimerTask = new TimerTask() { public void run() { MPDApplication app = (MPDApplication) getApplication(); try { if (lastSentVol != progress.getProgress()) { lastSentVol = progress.getProgress(); app.oMPDAsyncHelper.oMPD.setVolume(lastSentVol); } } catch (MPDServerException e) { e.printStackTrace(); } } int lastSentVol = -1; SeekBar progress; public TimerTask setProgress(SeekBar prg) { progress = prg; return this; } }.setProgress(seekBar); volTimer.scheduleAtFixedRate(volTimerTask, 0, 100); } public void onStopTrackingTouch(SeekBar seekBar) { volTimerTask.cancel(); // Afraid this will run syncronious volTimerTask.run(); /* * try { MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.oMPD.setVolume(progress); } catch * (MPDServerException e) { e.printStackTrace(); } */ } }); progressBarTrack.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } public void onStopTrackingTouch(SeekBar seekBar) { MPDApplication app = (MPDApplication) getApplication(); Runnable async = new Runnable() { // @SuppressWarnings("unchecked") @Override public void run() { try { MPDApplication app = (MPDApplication) getApplication(); app.oMPDAsyncHelper.oMPD.seek((int) progress); } catch (MPDServerException e) { e.printStackTrace(); } } public int progress; public Runnable setProgress(int prg) { progress = prg; return this; } }.setProgress(seekBar.getProgress()); app.oMPDAsyncHelper.execAsync(async); /* * try { MPDApplication app = (MPDApplication)getApplication(); app.oMPDAsyncHelper.oMPD.seek((int)progress); } catch * (MPDServerException e) { e.printStackTrace(); } */ } }); songNameText.setText(getResources().getString(R.string.notConnected)); myLogger.log(Level.INFO, "Initialization succeeded"); } private class ButtonEventHandler implements Button.OnClickListener, Button.OnLongClickListener { public void onClick(View v) { MPDApplication app = (MPDApplication) getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; Intent i = null; try { switch (v.getId()) { case R.id.next: mpd.next(); if (((MPDApplication) getApplication()).isStreamingMode()) { i = new Intent(app, StreamingService.class); i.setAction("com.namelessdev.mpdroid.RESET_STREAMING"); startService(i); } break; case R.id.prev: mpd.previous(); if (((MPDApplication) getApplication()).isStreamingMode()) { i = new Intent(app, StreamingService.class); i.setAction("com.namelessdev.mpdroid.RESET_STREAMING"); startService(i); } break; case R.id.back: mpd.seek(lastElapsedTime - TRACK_STEP); break; case R.id.forward: mpd.seek(lastElapsedTime + TRACK_STEP); break; case R.id.playpause: /** * If playing or paused, just toggle state, otherwise start playing. * * @author slubman */ String state = mpd.getStatus().getState(); if (state.equals(MPDStatus.MPD_STATE_PLAYING) || state.equals(MPDStatus.MPD_STATE_PAUSED)) { mpd.pause(); } else { mpd.play(); } break; } } catch (MPDServerException e) { myLogger.log(Level.WARNING, e.getMessage()); } } public boolean onLongClick(View v) { MPDApplication app = (MPDApplication) getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; try { switch (v.getId()) { case R.id.playpause: // Implements the ability to stop playing (may be useful for streams) mpd.stop(); Intent i; if (((MPDApplication) getApplication()).isStreamingMode()) { i = new Intent(app, StreamingService.class); i.setAction("com.namelessdev.mpdroid.STOP_STREAMING"); startService(i); } break; default: return false; } return true; } catch (MPDServerException e) { } return true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { MPDApplication app = (MPDApplication) getApplication(); try { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: if (((MPDApplication) getApplication()).isStreamingMode()) { return super.onKeyDown(keyCode, event); } else { progressBarVolume.incrementProgressBy(VOLUME_STEP); app.oMPDAsyncHelper.oMPD.adjustVolume(VOLUME_STEP); return true; } case KeyEvent.KEYCODE_VOLUME_DOWN: if (((MPDApplication) getApplication()).isStreamingMode()) { return super.onKeyDown(keyCode, event); } else { progressBarVolume.incrementProgressBy(-VOLUME_STEP); app.oMPDAsyncHelper.oMPD.adjustVolume(-VOLUME_STEP); return true; } case KeyEvent.KEYCODE_DPAD_LEFT: app.oMPDAsyncHelper.oMPD.previous(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: app.oMPDAsyncHelper.oMPD.next(); return true; default: return super.onKeyDown(keyCode, event); } } catch (MPDServerException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mpd_mainmenu, menu); /* * menu.add(0, LIBRARY, 1, R.string.libraryTabActivity).setIcon(R.drawable.ic_menu_music_library); menu.add(0, PLAYLIST, 3, * R.string.playlist).setIcon(R.drawable.ic_menu_pmix_playlist); menu.add(0, STREAM, 4, * R.string.stream).setIcon(android.R.drawable.ic_menu_upload_you_tube); menu.add(0, SETTINGS, 5, * R.string.settings).setIcon(android.R.drawable.ic_menu_preferences); */ return result; } @Override public boolean onTouchEvent(MotionEvent event) { if (gestureDetector.onTouchEvent(event)) return true; return false; } // Most of this comes from class MyGestureDetector extends SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private Activity context = null; public MyGestureDetector(Activity activity) { context = activity; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { // Next Toast.makeText(context, getResources().getString(R.string.next), Toast.LENGTH_SHORT).show(); MPDApplication app = (MPDApplication) getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; mpd.next(); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { // Previous Toast.makeText(context, getResources().getString(R.string.previous), Toast.LENGTH_SHORT).show(); MPDApplication app = (MPDApplication) getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; mpd.previous(); } } catch (Exception e) { // nothing } return false; } } @Override public boolean onPrepareOptionsMenu(Menu menu) { MPDApplication app = (MPDApplication) getApplication(); MPD mpd = app.oMPDAsyncHelper.oMPD; if (!mpd.isConnected()) { if (menu.findItem(CONNECT) == null) { menu.findItem(R.id.GMM_LibTab).setEnabled(false); menu.findItem(R.id.GMM_Playlist).setEnabled(false); menu.findItem(R.id.GMM_Stream).setEnabled(false); menu.add(0, CONNECT, 0, R.string.connect); } } else { if (menu.findItem(CONNECT) != null) { menu.findItem(R.id.GMM_LibTab).setEnabled(true); menu.findItem(R.id.GMM_Playlist).setEnabled(true); menu.findItem(R.id.GMM_Stream).setEnabled(true); menu.removeItem(CONNECT); } } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i = null; // Handle item selection switch (item.getItemId()) { /* * TODO: Remove this code it seems unused case ARTISTS: i = new Intent(this, ArtistsActivity.class); //startActivityForResult(i, * ARTISTS); return true; case ALBUMS: i = new Intent(this, AlbumsActivity.class); //startActivityForResult(i, ALBUMS); return true; * case FILES: i = new Intent(this, FSActivity.class); //startActivityForResult(i, FILES); return true; */ case R.id.GMM_LibTab: i = new Intent(this, LibraryTabActivity.class); startActivity(i); return true; case R.id.GMM_Settings: if (((MPDApplication) getApplication()).oMPDAsyncHelper.oMPD.isMpdConnectionNull()) { startActivityForResult(new Intent(this, WifiConnectionSettings.class), SETTINGS); } else { i = new Intent(this, SettingsActivity.class); startActivityForResult(i, SETTINGS); } return true; case R.id.GMM_Playlist: i = new Intent(this, PlaylistActivity.class); startActivity(i); // TODO juste pour s'y retrouver return true; case CONNECT: ((MPDApplication) getApplication()).connect(); return true; case R.id.GMM_Stream: if (((MPDApplication) getApplication()).isStreamingMode()) { // yeah, yeah getApplication for that may be ugly but ... i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.DIE"); startService(i); ((MPDApplication) getApplication()).setStreamingMode(false); // Toast.makeText(this, "MPD Streaming Stopped", Toast.LENGTH_SHORT).show(); } else { i = new Intent(this, StreamingService.class); i.setAction("com.namelessdev.mpdroid.START_STREAMING"); startService(i); ((MPDApplication) getApplication()).setStreamingMode(true); // Toast.makeText(this, "MPD Streaming Started", Toast.LENGTH_SHORT).show(); } default: return super.onOptionsItemSelected(item); } } // private MPDPlaylist playlist; public void playlistChanged(MPDPlaylistChangedEvent event) { // Can someone explain why this is nessesary? // Maybe the song gets changed before the playlist? // Makes little sense tho. try { updateTrackInfo(); } catch (Exception e) { e.printStackTrace(); } } public void randomChanged(MPDRandomChangedEvent event) { // TODO Auto-generated method stub } public void repeatChanged(MPDRepeatChangedEvent event) { // TODO Auto-generated method stub } public void stateChanged(MPDStateChangedEvent event) { MPDStatus status = event.getMpdStatus(); String state = status.getState(); if (state != null) { if (state.equals(MPDStatus.MPD_STATE_PLAYING)) { ImageButton button = (ImageButton) findViewById(R.id.playpause); if (newUI) { button.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_pause)); } else { button.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_media_pause)); } } else { ImageButton button = (ImageButton) findViewById(R.id.playpause); if (newUI) { button.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_play)); } else { button.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_media_play)); } } } } private String lastArtist = ""; private String lastAlbum = ""; public void updateTrackInfo() { new updateTrackInfoAsync().execute((MPDStatus[]) null); } public void updateTrackInfo(MPDStatus status) { new updateTrackInfoAsync().execute(status); } public class updateTrackInfoAsync extends AsyncTask<MPDStatus, Void, Boolean> { Music actSong = null; MPDStatus status = null; @Override protected Boolean doInBackground(MPDStatus... params) { if (params == null) { MPDApplication app = (MPDApplication) getApplication(); try { // A recursive call doesn't seem that bad here. return doInBackground(app.oMPDAsyncHelper.oMPD.getStatus()); } catch (MPDServerException e) { e.printStackTrace(); } return false; } if (params[0] != null) { String state = params[0].getState(); if (state != null) { int songId = params[0].getSongPos(); if (songId >= 0) { MPDApplication app = (MPDApplication) getApplication(); actSong = app.oMPDAsyncHelper.oMPD.getPlaylist().getMusic(songId); status = params[0]; return true; } } } return false; } @Override protected void onPostExecute(Boolean result) { if (result) { String artist = null; String title = null; String album = null; int songMax = 0; if (actSong == null || status.getPlaylistLength() == 0) { title = getResources().getString(R.string.noSongInfo); } else { Log.d("MPDroid", "We did find an artist"); artist = actSong.getArtist(); title = actSong.getTitle(); album = actSong.getAlbum(); songMax = (int) actSong.getTime(); } artist = artist == null ? "" : artist; title = title == null ? "" : title; album = album == null ? "" : album; artistNameText.setText(artist); songNameText.setText(title); albumNameText.setText(album); progressBarTrack.setMax(songMax); if (!lastAlbum.equals(album) || !lastArtist.equals(artist)) { // coverSwitcher.setVisibility(ImageSwitcher.INVISIBLE); if (enableLastFM) { coverSwitcherProgress.setVisibility(ProgressBar.VISIBLE); oCoverAsyncHelper.downloadCover(artist, album); } else { // Dirty hack ? Maybe. I don't feel like writing a new function. onCoverNotFound(); } lastArtist = artist; lastAlbum = album; } } else { artistNameText.setText(""); songNameText.setText(R.string.noSongInfo); albumNameText.setText(""); progressBarTrack.setMax(0); } } } public void trackChanged(MPDTrackChangedEvent event) { updateTrackInfo(event.getMpdStatus()); } public void updateStateChanged(MPDUpdateStateChangedEvent event) { // TODO Auto-generated method stub } @Override public void connectionStateChanged(MPDConnectionStateChangedEvent event) { // TODO Auto-generated method stub checkConnected(); /* * MPDStatus status = event.getMpdStatus(); * * String state = status.getState(); */ } public void checkConnected() { connected = ((MPDApplication) getApplication()).oMPDAsyncHelper.oMPD.isConnected(); if (connected) { songNameText.setText(getResources().getString(R.string.noSongInfo)); } else { songNameText.setText(getResources().getString(R.string.notConnected)); } return; } public void volumeChanged(MPDVolumeChangedEvent event) { progressBarVolume.setProgress(event.getMpdStatus().getVolume()); } @Override protected void onPause() { super.onPause(); myLogger.log(Level.INFO, "onPause"); } @Override protected void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.oMPDAsyncHelper.removeStatusChangeListener(this); app.oMPDAsyncHelper.removeTrackPositionListener(this); app.unsetActivity(this); myLogger.log(Level.INFO, "onStop"); } @Override protected void onDestroy() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); settings.unregisterOnSharedPreferenceChangeListener(this); myLogger.log(Level.INFO, "onDestroy"); super.onDestroy(); } public SeekBar getVolumeSeekBar() { return progressBarVolume; } public SeekBar getProgressBarTrack() { return progressBarTrack; } public void trackPositionChanged(MPDTrackPositionChangedEvent event) { MPDStatus status = event.getMpdStatus(); lastElapsedTime = status.getElapsedTime(); lastSongTime = status.getTotalTime(); trackTime.setText(timeToString(lastElapsedTime) + " - " + timeToString(lastSongTime)); progressBarTrack.setProgress((int) status.getElapsedTime()); } private static String timeToString(long seconds) { long min = seconds / 60; long sec = seconds - min * 60; return (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec); } public static void notifyUser(String message, Context context) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } public void onCoverDownloaded(Bitmap cover) { coverSwitcherProgress.setVisibility(ProgressBar.INVISIBLE); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if (cover != null) { cover.setDensity((int) metrics.density); BitmapDrawable myCover = new BitmapDrawable(cover); coverSwitcher.setImageDrawable(myCover); // coverSwitcher.setVisibility(ImageSwitcher.VISIBLE); coverSwitcher.showNext(); // Little trick so the animation gets displayed coverSwitcher.showPrevious(); } else { // Should not be happening, but happened. onCoverNotFound(); } } public void onCoverNotFound() { coverSwitcherProgress.setVisibility(ProgressBar.INVISIBLE); coverSwitcher.setImageResource(R.drawable.gmpcnocover); // coverSwitcher.setVisibility(ImageSwitcher.VISIBLE); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals("enableLastFM")) { enableLastFM = sharedPreferences.getBoolean("enableLastFM", true); } } }
package hulop.hokoukukan.bean; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.wink.json4j.JSONArray; import org.apache.wink.json4j.JSONException; import org.apache.wink.json4j.JSONObject; import org.jgrapht.WeightedGraph; import org.jgrapht.alg.DijkstraShortestPath; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.SimpleDirectedWeightedGraph; import hulop.hokoukukan.utils.DBAdapter; public class RouteSearchBean { public static final DBAdapter adapter = DatabaseBean.adapter; private static final double WEIGHT_IGNORE = Double.MAX_VALUE; private static final double ESCALATOR_WEIGHT = 100, STAIR_WEIGHT = 300, ELEVATOR_WEIGHT = 300; private long mLastInit; private JSONObject mNodeMap, mTempNode, mTempLink1, mTempLink2; private JSONArray mFeatures, mLandmarks, mDoors; private Set<String> mElevatorNodes; public RouteSearchBean() { } public void init(double[] point, double distance, String lang, boolean cache) throws JSONException { System.out.println("RouteSearchBean init lang=" + lang); RouteData rd = cache ? RouteData.getCache(point, distance) : new RouteData(point, distance); mTempNode = mTempLink1 = mTempLink2 = null; mNodeMap = rd.getNodeMap(); mFeatures = rd.getFeatures(); mLandmarks = rd.getLandmarks(lang); mDoors = rd.getDoors(); mElevatorNodes = rd.getElevatorNodes(); mLastInit = System.currentTimeMillis(); } public long getLastInit() { return mLastInit; } public JSONObject getNodeMap() { return mNodeMap; } public JSONArray getFeatures() { return mFeatures; } public JSONArray getLandmarks() { return mLandmarks; } public Object getDirection(String from, String to, Map<String, String> conditions) throws JSONException { mLastInit = System.currentTimeMillis(); mTempNode = mTempLink1 = mTempLink2 = null; JSONObject fromPoint = getPoint(from), toPoint = getPoint(to); if (fromPoint != null) { from = findNearestLink(fromPoint); if (from == null) { return null; } if (!mNodeMap.has(from)) { for (Object feature : mFeatures) { JSONObject json = (JSONObject) feature; if (from.equals(json.get("_id"))) { try { from = createTempNode(fromPoint, json); } catch (Exception e) { e.printStackTrace(); } break; } } } } else { from = extractNode(from); } if (toPoint != null) { to = adapter.findNearestNode(new double[] { toPoint.getDouble("lng"), toPoint.getDouble("lat") }, toPoint.has("floors") ? toPoint.getJSONArray("floors") : null); } if (from != null && from.equals(extractNode(to))) { return new JSONObject().put("error", "zero-distance"); } DirectionHandler dh = new DirectionHandler(from, to, conditions); for (Object feature : mFeatures) { dh.add(feature); } if (mTempNode != null) { dh.add(mTempLink1); dh.add(mTempLink2); } return dh.getResult(); } private class DirectionHandler { private WeightedGraph<String, DefaultWeightedEdge> g = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>( DefaultWeightedEdge.class); private Map<Object, JSONObject> linkMap = new HashMap<Object, JSONObject>(); private JSONArray result = new JSONArray(); private String from, to; private Map<String, String> conditions; public DirectionHandler(String from, String to, Map<String, String> conditions) { this.from = from; this.to = to; this.conditions = conditions; } public void add(Object feature) throws JSONException { JSONObject json = (JSONObject) feature; JSONObject properties = json.getJSONObject("properties"); switch (properties.getString("category")) { case "": if (!properties.has("ID") || !properties.has("ID")) { break; } String start = properties.getString("ID"); String end = properties.getString("ID"); double weight = properties.has("") ? Double.parseDouble(properties.getString("")) : 10.0f; weight = adjustAccWeight(properties, conditions, weight); if (weight == WEIGHT_IGNORE) { break; } if (from == null) { try { properties.put("sourceHeight", getHeight(start)); properties.put("targetHeight", getHeight(end)); } catch (Exception e) { } result.add(json); break; } g.addVertex(start); g.addVertex(end); DefaultWeightedEdge startEnd = null, endStart = null; switch (properties.getString("")) { case "1": startEnd = g.addEdge(start, end); break; case "2": endStart = g.addEdge(end, start); break; default: startEnd = g.addEdge(start, end); endStart = g.addEdge(end, start); break; } if (startEnd != null) { double add = !mElevatorNodes.contains(start) && mElevatorNodes.contains(end) ? ELEVATOR_WEIGHT : 0; g.setEdgeWeight(startEnd, weight + add); linkMap.put(startEnd, json); } if (endStart != null) { double add = mElevatorNodes.contains(start) && !mElevatorNodes.contains(end) ? ELEVATOR_WEIGHT : 0; g.setEdgeWeight(endStart, weight + add); linkMap.put(endStart, json); } break; } } public JSONArray getResult() { if (from != null) { try { // System.out.println(from + " - " + to + " - " + g.toString()); double lastWeight = Double.MAX_VALUE; List<DefaultWeightedEdge> path = null; for (String t : to.split("\\|")) { t = t.trim(); if (t.length() > 0) { try { List<DefaultWeightedEdge> p = DijkstraShortestPath.findPathBetween(g, from, extractNode(t)); if (p != null && p.size() > 0) { double totalWeight = 0; for (DefaultWeightedEdge edge : p) { totalWeight += g.getEdgeWeight(edge); } if (lastWeight > totalWeight) { lastWeight = totalWeight; path = p; to = t; } } } catch (Exception e) { System.err.println("No route to " + t); } } } if (path != null && path.size() > 0) { JSONObject fromNode = (JSONObject) getNode(from).clone(); result.add(fromNode); for (DefaultWeightedEdge edge : path) { JSONObject link = linkMap.get(edge); try { JSONObject properties = link.getJSONObject("properties"); String edgeSource = g.getEdgeSource(edge); String edgeTarget = g.getEdgeTarget(edge); String sourceDoor = getDoor(edgeSource); String targetDoor = getDoor(edgeTarget); properties.put("sourceNode", edgeSource); properties.put("targetNode", edgeTarget); properties.put("sourceHeight", getHeight(edgeSource)); properties.put("targetHeight", getHeight(edgeTarget)); if (sourceDoor != null) { properties.put("sourceDoor", sourceDoor); } else { properties.remove("sourceDoor"); } if (targetDoor != null) { properties.put("targetDoor", targetDoor); } else { properties.remove("targetDoor"); } } catch (Exception e) { e.printStackTrace(); } result.add(link); } JSONObject toNode = (JSONObject) getNode(extractNode(to)).clone(); toNode.put("_id", to); result.add(toNode); } // System.out.println(new KShortestPaths(g, from, // 3).getPaths(to)); } catch (Exception e) { e.printStackTrace(); } } return result; } private double adjustAccWeight(JSONObject properties, Map<String, String> conditions, double weight) throws JSONException { String linkType = properties.has("") ? properties.getString("") : ""; switch (linkType) { case "10": // Elevator weight = 0.0f; break; case "7": // Moving walkway weight *= 0.5f; break; case "11": // Escalator weight = ESCALATOR_WEIGHT; break; case "12": // Stairs weight = STAIR_WEIGHT; break; } double penarty = Math.max(weight, 10.0f) * 9; String width = properties.has("") ? properties.getString("") : ""; // 0: less than 1m, // 1: >1m & <1.5m, // 2: >1.5m & <2m, // 3: >2m // 9: unknown switch (conditions.get("min_width")) { case "1": if (width.equals("0") || width.equals("1") || width.equals("2") || width.equals("9")) { return WEIGHT_IGNORE; } break; case "2": // >1.5m if (width.equals("0") || width.equals("1") || width.equals("9")) { return WEIGHT_IGNORE; } break; case "3": // >1.0m if (width.equals("0") || width.equals("9")) { return WEIGHT_IGNORE; } break; case "8": // Avoid if (width.equals("0") || width.equals("1") || width.equals("2") || width.equals("9")) { weight += penarty; } break; } float slope = properties.has("1") ? Float.parseFloat(properties.getString("1")) : 0; // Maximum slope value (%) along the link switch (conditions.get("slope")) { case "1": if (slope >= 8.0) { return WEIGHT_IGNORE; } break; case "2": if (slope >= 10.0) { return WEIGHT_IGNORE; } break; case "8": // Avoid if (slope >= 8.0) { weight += penarty; } break; } String road = properties.has("") ? properties.getString("") : ""; // 0: no problem, 1: dirt, 2: gravel, 3: other, 9: unknown switch (conditions.get("road_condition")) { case "1": // No problem if (road.equals("1") || road.equals("2") || road.equals("3") || road.equals("9")) { return WEIGHT_IGNORE; } break; case "8": // Avoid if (road.equals("1") || road.equals("2") || road.equals("3") || road.equals("9")) { weight += penarty; } break; } String bump = properties.has("") ? properties.getString("") : ""; // 0: less than 2cm, 1: 2~5cm, 2: 5~10cm, 3: more than 10cm, 9: unknown // (assign max bump height for whole link) switch (conditions.get("deff_LV")) { case "1": // <2cm if (bump.equals("1") || bump.equals("2") || bump.equals("3") || bump.equals("9")) { return WEIGHT_IGNORE; } break; case "2": // <5cm if (bump.equals("2") || bump.equals("3") || bump.equals("9")) { return WEIGHT_IGNORE; } break; case "3": // <10cm if (bump.equals("3") || bump.equals("9")) { return WEIGHT_IGNORE; } break; case "8": // Avoid if (bump.equals("1") || bump.equals("2") || bump.equals("3") || bump.equals("9")) { weight += penarty; } break; } int steps = properties.has("") ? Integer.parseInt(properties.getString("")) : 0; // number of steps along a stairway // if (linkType.equals("12") && steps == 0) { // System.out.println("Error: steps should > 0"); String rail = properties.has("") ? properties.getString("") : ""; // 0: no, 1: on the right, 2: on the left, 3: both sides, 9: unknown // (link direction - start node to end node) switch (conditions.get("stairs")) { case "1": // Do not use if (steps > 0) { return WEIGHT_IGNORE; } break; case "2": // Use with hand rail if (steps > 0 && !(rail.equals("1") || rail.equals("2") || rail.equals("3"))) { return WEIGHT_IGNORE; } break; case "8": // Avoid if (steps > 0) { weight += penarty; } break; } String elevator = properties.has("") ? properties.getString("") : ""; // 0: not included, 1: braille and audio, 2: wheelchair, 3: 1&2, 9: // unknown switch (conditions.get("elv")) { case "1": // Do not use if (elevator.equals("0") || elevator.equals("1") || elevator.equals("2") || elevator.equals("3") || elevator.equals("9")) { return WEIGHT_IGNORE; } case "2": // Wheel chair supported if (elevator.equals("0") || elevator.equals("1") || elevator.equals("9")) { return WEIGHT_IGNORE; } case "8": // Avoid if (elevator.equals("0") || elevator.equals("1") || elevator.equals("9")) { weight += penarty; } break; } switch (conditions.get("esc")) { case "1": // Do not use if (linkType.equals("11")) { return WEIGHT_IGNORE; } case "8": // Avoid if (linkType.equals("11")) { weight += penarty; } break; } if (properties.has("") && "1".equals(properties.getString(""))) { // 0: no, 1: yes, 9: unknown (tactile paving along the path/link) if ("1".equals(conditions.get("tactile_paving"))) { weight = weight / 3; } } return weight; } } private static String extractNode(String id) { return id != null ? id.split(":")[0] : null; } private static JSONObject getPoint(String node) { if (node != null) { String[] params = node.split(":"); if (params.length >= 3 && params[0].equals("latlng")) { JSONObject point = new JSONObject(); try { if (params.length > 3) { List<String> floors = new ArrayList<String>(); floors.add(params[3]); if (params[3].equals("1")) { floors.add("0"); } point.put("floors", floors); } return point.put("lat", Double.parseDouble(params[1])).put("lng", Double.parseDouble(params[2])); } catch (JSONException e) { e.printStackTrace(); } } } return null; } private boolean isNode(String id) { return tempNodeID.equals(id) ? mTempNode != null : mNodeMap.has(id); } private JSONObject getNode(String id) throws JSONException { return tempNodeID.equals(id) ? mTempNode : mNodeMap.getJSONObject(id); } private float getHeight(String node) throws NumberFormatException, JSONException { return Float.parseFloat(getNode(node).getJSONObject("properties").getString("").replace("B", "-")); } private String getDoor(String node) throws JSONException { if (countLinks(node) <= 2) { for (Object p : mDoors) { JSONObject properties = (JSONObject) p; if (node.equals(properties.getString("ID"))) { return properties.getString(""); } } } return null; } private int countLinks(String node) { try { int count = 0; JSONObject properties = getNode(node).getJSONObject("properties"); for (int i = 1; i <= 10; i++) { if (properties.has("ID" + i)) { count++; } } return count; } catch (Exception e) { e.printStackTrace(); } return 0; } private static final double METERS_PER_DEGREE = 60.0 * 1.1515 * 1.609344 * 1000; private static double deg2rad(double deg) { return (deg * Math.PI / 180.0); } public static double calcDistance(double[] point1, double[] point2) { double theta = deg2rad(point1[0] - point2[0]); double lat1 = deg2rad(point1[1]), lat2 = deg2rad(point2[1]); double dist = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(theta); return METERS_PER_DEGREE * Math.acos(dist) * 180.0 / Math.PI; } static final String INVALID_LINKS = "|7|10|11|"; private String findNearestLink(JSONObject fromPoint) { try { List<String> floors = fromPoint.has("floors") ? fromPoint.getJSONArray("floors") : null; List<JSONObject> links = new ArrayList<JSONObject>(); for (Object feature : mFeatures) { JSONObject json = (JSONObject) feature; JSONObject properties = json.getJSONObject("properties"); if (properties.has("ID") && properties.has("ID") && INVALID_LINKS.indexOf("|" + properties.getString("") + "|") == -1) { String startID = properties.getString("ID"); String endID = properties.getString("ID"); if (isNode(startID) && isNode(endID)) { if (floors == null) { links.add(json); } else { String startHeight = getNode(startID).getJSONObject("properties").getString(""); String endHeight = getNode(endID).getJSONObject("properties").getString(""); if (floors.indexOf(startHeight) != -1 && floors.indexOf(endHeight) != -1) { links.add(json); } } } } } if (links.size() > 0) { final Point2D.Double pt = new Point2D.Double(fromPoint.getDouble("lng"), fromPoint.getDouble("lat")); links.sort(new Comparator<JSONObject>() { @Override public int compare(JSONObject o1, JSONObject o2) { try { double dist1 = calc2Ddistance(o1.getJSONObject("geometry").getJSONArray("coordinates"), pt, null); double dist2 = calc2Ddistance(o2.getJSONObject("geometry").getJSONArray("coordinates"), pt, null); if (dist1 != dist2) { return dist1 < dist2 ? -1 : 1; } } catch (Exception e) { e.printStackTrace(); } return 0; } }); return links.get(0).getString("_id"); } } catch (JSONException e) { e.printStackTrace(); } return null; } private static double calc2Ddistance(JSONArray coordinates, Point2D.Double pt, int[] seg) throws Exception { double result = -1; Point2D.Double from = get2DPoint(coordinates, 0); for (int i = 1; i < coordinates.size() && result != 0.0; i++) { Point2D.Double to = get2DPoint(coordinates, i); double dist = Line2D.ptSegDist(from.x, from.y, to.x, to.y, pt.x, pt.y); from = to; if (result < 0 || dist < result) { result = dist; if (seg != null) { seg[0] = i - 1; } } } return result; } private static Point2D.Double get2DPoint(JSONArray coordinates, int index) throws Exception { JSONArray coord = coordinates.getJSONArray(index); return new Point2D.Double(coord.getDouble(0), coord.getDouble(1)); } static final String tempNodeID = "_TEMP_NODE_", tempLink1ID = "_TEMP_LINK1_", tempLink2ID = "_TEMP_LINK2_"; private String createTempNode(JSONObject point, JSONObject link) throws Exception { JSONArray linkCoords = link.getJSONObject("geometry").getJSONArray("coordinates"); JSONArray nodeCoord = new JSONArray().put(point.getDouble("lng")).put(point.getDouble("lat")); Object pos = getOrthoCenter(linkCoords, nodeCoord, link.getJSONObject("properties")); int lineSeg = 0; if (pos instanceof String) { return (String) pos; } else if (pos instanceof JSONObject) { JSONObject o = (JSONObject) pos; nodeCoord = new JSONArray().put(o.getDouble("x")).put(o.getDouble("y")); lineSeg = o.getInt("seg"); } // Create temp node String tempFloor = point.has("floors") ? point.getJSONArray("floors").getString(0) : "0"; mTempNode = new JSONObject(); final JSONObject geometry = new JSONObject(); final JSONObject nodeProp = new JSONObject(); geometry.put("type", "Point"); geometry.put("coordinates", nodeCoord); nodeProp.put("category", ""); nodeProp.put("ID", tempNodeID); nodeProp.put("", tempFloor); nodeProp.put("ID1", tempLink1ID); nodeProp.put("ID2", tempLink2ID); mTempNode.put("_id", tempNodeID); mTempNode.put("type", "Feature"); mTempNode.put("geometry", geometry); mTempNode.put("properties", nodeProp); // System.out.println(tempNode.toString(4)); // Create temp links mTempLink1 = new JSONObject(link.toString()); mTempLink2 = new JSONObject(link.toString()); mTempLink1.put("_id", tempLink1ID); mTempLink2.put("_id", tempLink2ID); final JSONObject link1Geo = mTempLink1.getJSONObject("geometry"), link2Geo = mTempLink2.getJSONObject("geometry"); JSONArray link1Coords = link1Geo.getJSONArray("coordinates"); JSONArray link2Coords = link2Geo.getJSONArray("coordinates"); for (int i = 0; i < linkCoords.length(); i++) { if (i > lineSeg) { link1Coords.remove(link1Coords.length() - 1); } else { link2Coords.remove(0); } } JSONArray link1Last = link1Coords.getJSONArray(link1Coords.length() - 1); if (!link1Last.equals(nodeCoord)) { link1Coords.add(nodeCoord); } JSONArray link2first = link2Coords.getJSONArray(0); if (!link2first.equals(nodeCoord)) { link2Coords.add(0, nodeCoord); } final JSONObject link1Prop = mTempLink1.getJSONObject("properties"), link2Prop = mTempLink2.getJSONObject("properties"); link1Prop.put("ID", tempLink1ID); link1Prop.put("ID", tempNodeID); link2Prop.put("ID", tempLink2ID); link2Prop.put("ID", tempNodeID); setLength(mTempLink1); setLength(mTempLink2); return tempNodeID; } private static void setLength(JSONObject link) throws Exception { JSONArray linkCoords = link.getJSONObject("geometry").getJSONArray("coordinates"); double length = 0; for (int i = 0; i < linkCoords.length() - 1; i++) { JSONArray from = linkCoords.getJSONArray(i); JSONArray to = linkCoords.getJSONArray(i + 1); length += calcDistance(new double[] { from.getDouble(0), from.getDouble(1) }, new double[] { to.getDouble(0), to.getDouble(1) }); } link.getJSONObject("properties").put("", Double.toString(length)); } private static Object getOrthoCenter(JSONArray line, JSONArray point, JSONObject linkProp) throws Exception { Point2D.Double c = new Point2D.Double(point.getDouble(0), point.getDouble(1)); int[] seg = new int[] { 0 }; calc2Ddistance(line, c, seg); JSONArray start = line.getJSONArray(seg[0]); JSONArray end = line.getJSONArray(seg[0] + 1); Point2D.Double a = new Point2D.Double(start.getDouble(0), start.getDouble(1)); Point2D.Double b = new Point2D.Double(end.getDouble(0), end.getDouble(1)); double distCA = Point2D.distance(a.x, a.y, c.x, c.y); double distCB = Point2D.distance(b.x, b.y, c.x, c.y); double distCX = Line2D.ptSegDist(a.x, a.y, b.x, b.y, c.x, c.y); if (distCA <= distCX && seg[0] == 0) { return linkProp.getString("ID"); } else if (distCB <= distCX && seg[0] == line.length() - 2) { return linkProp.getString("ID"); } else { double distAB = Point2D.distance(a.x, a.y, b.x, b.y); double distAX = Math.sqrt(distCA * distCA - distCX * distCX); double timeAX = Math.max(0, Math.min(distAX / distAB, 1)); double x = (b.x - a.x) * timeAX + a.x; double y = (b.y - a.y) * timeAX + a.y; return new JSONObject().put("x", x).put("y", y).put("seg", seg[0]); } } static double[] CURRENT_POINT = { 139.77392703294754, 35.68662700502585 }; static double MAX_DISTANCE = 500; public static void main(String[] args) { try { RouteSearchBean search = new RouteSearchBean(); search.init(CURRENT_POINT, MAX_DISTANCE, "en", false); String from = "latlng:" + CURRENT_POINT[0] + ":" + CURRENT_POINT[1]; JSONArray landmarks = search.getLandmarks(); JSONObject toNode = landmarks.getJSONObject((int) ((Math.random() / 2 + 0.25) * landmarks.length())); String to = toNode.getString("node"); Object direction = search.getDirection(from, to, new HashMap<String, String>()); System.out.println(direction.toString()); System.out.println(from + " to " + toNode.getString("name")); } catch (JSONException e) { e.printStackTrace(); } } }
package edu.umd.cs.findbugs; import java.io.IOException; import java.io.Serializable; import javax.annotation.Nonnull; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLWriteable; /** * class to hold the user annotation and user designation for a BugInstance */ public class BugDesignation implements XMLWriteable, Serializable, Comparable<BugDesignation> { /** The default key for the user designation. * Bad things could happen if this key isn't in getUserDesignations() */ public static final String UNCLASSIFIED = "UNCLASSIFIED"; /** user designation -- value should be one of the keys * returned by I18N.getInstance().getUserDesignations() */ @NonNull private String designation = UNCLASSIFIED; public String toString() { String result = designation; if (user != null) result += " by " + user; if (annotationText != null && annotationText.length() > 0) result += " : " + annotationText; return result; } private boolean dirty; public boolean isDirty() { return dirty; } public void cleanDirty() { dirty = false; } private @javax.annotation.CheckForNull String user; public BugDesignation() {} /** * @param designation * @param timestamp * @param annotationText * @param user */ public BugDesignation(String designation, long timestamp, String annotationText, String user) { this.designation = designation; this.timestamp = timestamp; this.annotationText = annotationText; this.user = user; } public BugDesignation(BugDesignation that) { this(that.designation, that.timestamp, that.annotationText, that.user); } private long timestamp = System.currentTimeMillis(); /** free text from the user */ //TODO: make this @CheckForNull private String annotationText; /** return the user designation * E.g., "MOSTLY_HARMLESS", "CRITICAL", "NOT_A_BUG", etc. * * Note that this is the key, suitable for writing to XML, * but not for showing to the user. * @see I18N#getUserDesignation(String key) */ @NonNull public String getDesignationKey() { return designation; } /** set the user designation * E.g., "MOSTLY_HARMLESS", "CRITICAL", "NOT_A_BUG", etc. * * If the argument is null, it will be treated as UNCLASSIFIED. * * Note that this is the key, suitable for writing to XML, * but not what the user sees. Strange things could happen * if designationKey is not one of the keys returned by * I18N.instance().getUserDesignations(). * @see I18N#getUserDesignationKeys() */ public void setDesignationKey(String designationKey) { if (designation.equals(designationKey)) return; dirty = true; timestamp = System.currentTimeMillis(); designation = (designationKey!=null ? designationKey : UNCLASSIFIED); } @CheckForNull public String getUser() { return user; } public void setUser(String u) { user = u; } public long getTimestamp() { return timestamp; } public void setTimestamp(long ts) { if (timestamp != ts) { timestamp = ts; dirty = true; } } @CheckForNull public String getAnnotationText() { return annotationText; } @Nonnull public String getNonnullAnnotationText() { if (annotationText == null) return ""; return annotationText; } public void setAnnotationText(String s) { if (s.equals(annotationText)) return; dirty = true; annotationText = s; timestamp = System.currentTimeMillis(); } public void writeXML(XMLOutput xmlOutput) throws IOException { XMLAttributeList attributeList = new XMLAttributeList(); // all three of these xml attributes are optional if (designation != null && !UNCLASSIFIED.equals(designation)) attributeList.addAttribute("designation", designation); if (user != null && !"".equals(user)) attributeList.addAttribute("user", user); if (timestamp > 0) attributeList.addAttribute("timestamp", String.valueOf(timestamp)); if ((annotationText != null && !"".equals(annotationText))) { xmlOutput.openTag("UserAnnotation", attributeList); xmlOutput.writeCDATA(annotationText); xmlOutput.closeTag("UserAnnotation"); } else { xmlOutput.openCloseTag("UserAnnotation", attributeList); } } /** replace unset fields of this user designation with values set in the other */ public void merge(@CheckForNull BugDesignation other) { if (other == null) return; boolean changed = false; if ( (annotationText==null || annotationText.length()==0) && other.annotationText!=null && other.annotationText.length()>0) { annotationText = other.annotationText; dirty = true; changed = true; } if ( (designation==null || UNCLASSIFIED.equals(designation) || designation.length()==0) && other.designation!=null && other.designation.length()>0) { designation = other.designation; dirty = true; changed = true; } if (!changed) return; // if no changes don't even try to copy user or timestamp if ( (user==null || user.length()==0) && other.user!=null && other.user.length()>0) { user = other.user; } if (timestamp==0 && other.timestamp!=0) { timestamp = other.timestamp; } } public int hashCode() { int hash = (int) this.timestamp; if (user != null) hash += user.hashCode(); if (designation != null) hash += designation.hashCode(); if (annotationText != null) hash += annotationText.hashCode(); return hash; } public boolean equals(Object o) { if (!(o instanceof BugDesignation)) return false; return this.compareTo((BugDesignation)o) == 0; } public int compareTo(BugDesignation o) { if (this == o) return 0; int result = - Util.compare(this.timestamp, o.timestamp); if (result != 0) return result; result = Util.nullSafeCompareTo(this.user, o.user); if (result != 0) return result; result = Util.nullSafeCompareTo(this.designation, o.designation); if (result != 0) return result; result = Util.nullSafeCompareTo(this.annotationText, o.annotationText); if (result != 0) return result; return 0; } }
// T r a i n e r // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr.classifier.ui; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import org.audiveris.omr.WellKnowns; import org.audiveris.omr.classifier.Classifier; import org.audiveris.omr.classifier.ShapeClassifier; import org.audiveris.omr.constant.ConstantManager; import org.audiveris.omr.ui.OmrGui; import org.audiveris.omr.ui.util.Panel; import org.audiveris.omr.ui.util.UILookAndFeel; import org.audiveris.omr.ui.util.UIUtil; import org.jdesktop.application.Application; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Locale; import java.util.Observable; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; public class Trainer extends SingleFrameApplication { static { // We need class WellKnowns to be elaborated before anything else (when in standalone mode) WellKnowns.ensureLoaded(); } private static final Logger logger = LoggerFactory.getLogger(Trainer.class); /** The single instance of this class. */ private static volatile Trainer INSTANCE; /** Stand-alone run (vs part of Audiveris). */ private static boolean standAlone = false; /** Standard width for labels in DLUs. */ static final String LABEL_WIDTH = "50dlu"; /** Standard width for fields/buttons in DLUs. */ static final String FIELD_WIDTH = "30dlu"; /** An adapter triggered on window closing. */ private static final WindowAdapter windowCloser = new WindowAdapter() { @Override public void windowClosing (WindowEvent e) { // Store latest constant values ConstantManager.getInstance().storeResource(); // That's all folks ! System.exit(0); } }; /** Related frame. */ private JFrame frame; /** Panel for selection in repository. */ private final SelectionPanel selectionPanel; /** * Create an instance of Glyph Trainer (there should be just one) */ public Trainer () { // Create the companions selectionPanel = new SelectionPanel(); // Specific ending if stand alone if (!standAlone) { frame = defineLayout(new JFrame()); } else { INSTANCE = this; } } // getInstance // public static synchronized Trainer getInstance () { if (INSTANCE == null) { INSTANCE = new Trainer(); } return INSTANCE; } // launch // /** * (Re)activate the trainer tool */ public static void launch () { if (standAlone) { } else { final JFrame frame = getInstance().frame; OmrGui.getApplication().show(frame); UIUtil.unMinimize(frame); } } // main // /** * Just to allow stand-alone running of this class * * @param args not used */ public static void main (String... args) { standAlone = true; // Set UI Look and Feel UILookAndFeel.setUI(null); Locale.setDefault(Locale.ENGLISH); // Off we go... Application.launch(Trainer.class, args); } // initialize // @Override protected void initialize (String[] args) { logger.debug("Trainer. 1/initialize"); } // ready // @Override protected void ready () { logger.debug("Trainer. 3/ready"); frame.addWindowListener(windowCloser); } // startup // @Override protected void startup () { logger.debug("Trainer. 2/startup"); frame = defineLayout(getMainFrame()); show(frame); // Here we go... } // displayFrame // void displayFrame () { frame.toFront(); } // defineLayout // /** * Define the layout of components within the provided frame. * * @param frame the bare frame * @return the populated frame * */ private JFrame defineLayout (final JFrame frame) { frame.setName("TrainerFrame"); // For SAF life cycle FormLayout layout = new FormLayout("pref, 10dlu, pref", "pref, 10dlu, pref"); CellConstraints cst = new CellConstraints(); PanelBuilder builder = new PanelBuilder(layout, new Panel()); int r = 1; builder.add(selectionPanel.getComponent(), cst.xyw(1, r, 3, "center, fill")); r += 2; builder.add(definePanel(ShapeClassifier.getInstance()), cst.xy(1, r)); builder.add(definePanel(ShapeClassifier.getSecondInstance()), cst.xy(3, r)); frame.add(builder.getPanel()); // Resource injection ResourceMap resource = OmrGui.getApplication().getContext().getResourceMap(getClass()); resource.injectComponents(frame); return frame; } private JPanel definePanel (Classifier classifier) { final String pi = Panel.getPanelInterline(); FormLayout layout = new FormLayout("pref", "pref," + pi + ",pref," + pi + ",pref"); CellConstraints cst = new CellConstraints(); PanelBuilder builder = new PanelBuilder(layout, new TitledPanel(classifier.getName())); Task task = new Task(classifier); int r = 1; builder.add(new TrainingPanel(task, selectionPanel).getComponent(), cst.xy(1, r)); r += 2; builder.add(new ValidationPanel(task, selectionPanel, true).getComponent(), cst.xy(1, r)); r += 2; builder.add(new ValidationPanel(task, selectionPanel, false).getComponent(), cst.xy(1, r)); return builder.getPanel(); } // Task // /** * Class {@code Task} handles, for a given classifier, which activity is currently * being carried out, only one being current at any time. */ public static class Task extends Observable { /** * Enum {@code Activity} defines all activities in training. */ static enum Activity { /** No ongoing activity */ INACTIVE, /** Training on samples */ TRAINING, /** Validating classifier */ VALIDATION; } /** Managed classifier. */ public final Classifier classifier; /** Current activity. */ private Activity activity = Activity.INACTIVE; public Task (Classifier classifier) { this.classifier = classifier; } /** * Report the current training activity * * @return current activity */ public Activity getActivity () { return activity; } /** * Assign a new current activity and notify all observers * * @param activity */ public void setActivity (Activity activity) { this.activity = activity; setChanged(); notifyObservers(); } } // TitledPanel // private static class TitledPanel extends Panel { public TitledPanel (String title) { setBorder( BorderFactory.createTitledBorder( new EtchedBorder(), title, TitledBorder.CENTER, TitledBorder.TOP)); setInsets(30, 10, 10, 10); // TLBR } } }
package org.eclipse.bpmn2.impl; import java.util.Collection; import java.util.Date; import java.util.List; import org.eclipse.bpmn2.Activity; import org.eclipse.bpmn2.BoundaryEvent; import org.eclipse.bpmn2.Bpmn2Package; import org.eclipse.bpmn2.DataInputAssociation; import org.eclipse.bpmn2.DataOutputAssociation; import org.eclipse.bpmn2.FormalExpression; import org.eclipse.bpmn2.MultiInstanceLoopCharacteristics; import org.eclipse.bpmn2.StandardLoopCharacteristics; import org.eclipse.bpmn2.InputOutputSpecification; import org.eclipse.bpmn2.LoopCharacteristics; import org.eclipse.bpmn2.Property; import org.eclipse.bpmn2.ResourceRole; import org.eclipse.bpmn2.SequenceFlow; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.EObjectWithInverseEList; import org.eclipse.emf.ecore.util.FeatureMap; import org.eclipse.emf.ecore.util.InternalEList; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import com.founder.fix.bpmn2extensions.fixflow.SkipStrategy; import com.founder.fix.fixflow.core.event.BaseElementEvent; import com.founder.fix.fixflow.core.exception.FixFlowException; import com.founder.fix.fixflow.core.factory.ProcessObjectFactory; import com.founder.fix.fixflow.core.impl.Context; import com.founder.fix.fixflow.core.impl.expression.ExpressionMgmt; import com.founder.fix.fixflow.core.impl.runtime.TokenEntity; import com.founder.fix.fixflow.core.impl.util.EMFExtensionUtil; import com.founder.fix.fixflow.core.impl.util.GuidUtil; import com.founder.fix.fixflow.core.impl.util.StringUtil; import com.founder.fix.fixflow.core.runtime.ExecutionContext; /** * <!-- begin-user-doc --> An implementation of the model object ' * <em><b>Activity</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getIoSpecification <em>Io * Specification</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getBoundaryEventRefs <em> * Boundary Event Refs</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getProperties <em>Properties * </em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getDataInputAssociations <em> * Data Input Associations</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getDataOutputAssociations <em> * Data Output Associations</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getResources <em>Resources * </em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getLoopCharacteristics <em> * Loop Characteristics</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getCompletionQuantity <em> * Completion Quantity</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getDefault <em>Default</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#isIsForCompensation <em>Is For * Compensation</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ActivityImpl#getStartQuantity <em>Start * Quantity</em>}</li> * </ul> * </p> * * @generated */ public class ActivityImpl extends FlowNodeImpl implements Activity { /** * The cached value of the '{@link #getIoSpecification() * <em>Io Specification</em>}' containment reference. <!-- begin-user-doc * --> <!-- end-user-doc --> * * @see #getIoSpecification() * @generated * @ordered */ protected InputOutputSpecification ioSpecification; /** * The cached value of the '{@link #getBoundaryEventRefs() * <em>Boundary Event Refs</em>}' reference list. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getBoundaryEventRefs() * @generated * @ordered */ protected EList<BoundaryEvent> boundaryEventRefs; /** * The cached value of the '{@link #getProperties() <em>Properties</em>}' * containment reference list. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getProperties() * @generated * @ordered */ protected EList<Property> properties; /** * The cached value of the '{@link #getDataInputAssociations() * <em>Data Input Associations</em>}' containment reference list. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getDataInputAssociations() * @generated * @ordered */ protected EList<DataInputAssociation> dataInputAssociations; /** * The cached value of the '{@link #getDataOutputAssociations() * <em>Data Output Associations</em>}' containment reference list. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getDataOutputAssociations() * @generated * @ordered */ protected EList<DataOutputAssociation> dataOutputAssociations; /** * The cached value of the '{@link #getResources() <em>Resources</em>}' * containment reference list. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getResources() * @generated * @ordered */ protected EList<ResourceRole> resources; /** * The cached value of the '{@link #getLoopCharacteristics() * <em>Loop Characteristics</em>}' containment reference. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @see #getLoopCharacteristics() * @generated * @ordered */ protected LoopCharacteristics loopCharacteristics; /** * The default value of the '{@link #getCompletionQuantity() * <em>Completion Quantity</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #getCompletionQuantity() * @generated * @ordered */ protected static final int COMPLETION_QUANTITY_EDEFAULT = 1; /** * The cached value of the '{@link #getCompletionQuantity() * <em>Completion Quantity</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #getCompletionQuantity() * @generated * @ordered */ protected int completionQuantity = COMPLETION_QUANTITY_EDEFAULT; /** * The cached value of the '{@link #getDefault() <em>Default</em>}' * reference. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #getDefault() * @generated * @ordered */ protected SequenceFlow default_; /** * The default value of the '{@link #isIsForCompensation() * <em>Is For Compensation</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #isIsForCompensation() * @generated * @ordered */ protected static final boolean IS_FOR_COMPENSATION_EDEFAULT = false; /** * The cached value of the '{@link #isIsForCompensation() * <em>Is For Compensation</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #isIsForCompensation() * @generated * @ordered */ protected boolean isForCompensation = IS_FOR_COMPENSATION_EDEFAULT; /** * The default value of the '{@link #getStartQuantity() * <em>Start Quantity</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #getStartQuantity() * @generated * @ordered */ protected static final int START_QUANTITY_EDEFAULT = 1; /** * The cached value of the '{@link #getStartQuantity() * <em>Start Quantity</em>}' attribute. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @see #getStartQuantity() * @generated * @ordered */ protected int startQuantity = START_QUANTITY_EDEFAULT; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ protected ActivityImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return Bpmn2Package.Literals.ACTIVITY; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public InputOutputSpecification getIoSpecification() { return ioSpecification; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetIoSpecification(InputOutputSpecification newIoSpecification, NotificationChain msgs) { InputOutputSpecification oldIoSpecification = ioSpecification; ioSpecification = newIoSpecification; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__IO_SPECIFICATION, oldIoSpecification, newIoSpecification); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setIoSpecification(InputOutputSpecification newIoSpecification) { if (newIoSpecification != ioSpecification) { NotificationChain msgs = null; if (ioSpecification != null) msgs = ((InternalEObject) ioSpecification).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Bpmn2Package.ACTIVITY__IO_SPECIFICATION, null, msgs); if (newIoSpecification != null) msgs = ((InternalEObject) newIoSpecification).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Bpmn2Package.ACTIVITY__IO_SPECIFICATION, null, msgs); msgs = basicSetIoSpecification(newIoSpecification, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__IO_SPECIFICATION, newIoSpecification, newIoSpecification)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public List<BoundaryEvent> getBoundaryEventRefs() { if (boundaryEventRefs == null) { boundaryEventRefs = new EObjectWithInverseEList<BoundaryEvent>(BoundaryEvent.class, this, Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS, Bpmn2Package.BOUNDARY_EVENT__ATTACHED_TO_REF); } return boundaryEventRefs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public List<Property> getProperties() { if (properties == null) { properties = new EObjectContainmentEList<Property>(Property.class, this, Bpmn2Package.ACTIVITY__PROPERTIES); } return properties; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public List<DataInputAssociation> getDataInputAssociations() { if (dataInputAssociations == null) { dataInputAssociations = new EObjectContainmentEList<DataInputAssociation>(DataInputAssociation.class, this, Bpmn2Package.ACTIVITY__DATA_INPUT_ASSOCIATIONS); } return dataInputAssociations; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public List<DataOutputAssociation> getDataOutputAssociations() { if (dataOutputAssociations == null) { dataOutputAssociations = new EObjectContainmentEList<DataOutputAssociation>(DataOutputAssociation.class, this, Bpmn2Package.ACTIVITY__DATA_OUTPUT_ASSOCIATIONS); } return dataOutputAssociations; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public List<ResourceRole> getResources() { if (resources == null) { resources = new EObjectContainmentEList<ResourceRole>(ResourceRole.class, this, Bpmn2Package.ACTIVITY__RESOURCES); } return resources; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public LoopCharacteristics getLoopCharacteristics() { return loopCharacteristics; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public NotificationChain basicSetLoopCharacteristics(LoopCharacteristics newLoopCharacteristics, NotificationChain msgs) { LoopCharacteristics oldLoopCharacteristics = loopCharacteristics; loopCharacteristics = newLoopCharacteristics; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS, oldLoopCharacteristics, newLoopCharacteristics); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setLoopCharacteristics(LoopCharacteristics newLoopCharacteristics) { if (newLoopCharacteristics != loopCharacteristics) { NotificationChain msgs = null; if (loopCharacteristics != null) msgs = ((InternalEObject) loopCharacteristics).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS, null, msgs); if (newLoopCharacteristics != null) msgs = ((InternalEObject) newLoopCharacteristics).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS, null, msgs); msgs = basicSetLoopCharacteristics(newLoopCharacteristics, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS, newLoopCharacteristics, newLoopCharacteristics)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public int getCompletionQuantity() { return completionQuantity; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setCompletionQuantity(int newCompletionQuantity) { int oldCompletionQuantity = completionQuantity; completionQuantity = newCompletionQuantity; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__COMPLETION_QUANTITY, oldCompletionQuantity, completionQuantity)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public SequenceFlow getDefault() { return default_; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setDefault(SequenceFlow newDefault) { SequenceFlow oldDefault = default_; default_ = newDefault; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__DEFAULT, oldDefault, default_)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public boolean isIsForCompensation() { return isForCompensation; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setIsForCompensation(boolean newIsForCompensation) { boolean oldIsForCompensation = isForCompensation; isForCompensation = newIsForCompensation; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__IS_FOR_COMPENSATION, oldIsForCompensation, isForCompensation)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public int getStartQuantity() { return startQuantity; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public void setStartQuantity(int newStartQuantity) { int oldStartQuantity = startQuantity; startQuantity = newStartQuantity; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ACTIVITY__START_QUANTITY, oldStartQuantity, startQuantity)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS: return ((InternalEList<InternalEObject>) (InternalEList<?>) getBoundaryEventRefs()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bpmn2Package.ACTIVITY__IO_SPECIFICATION: return basicSetIoSpecification(null, msgs); case Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS: return ((InternalEList<?>) getBoundaryEventRefs()).basicRemove(otherEnd, msgs); case Bpmn2Package.ACTIVITY__PROPERTIES: return ((InternalEList<?>) getProperties()).basicRemove(otherEnd, msgs); case Bpmn2Package.ACTIVITY__DATA_INPUT_ASSOCIATIONS: return ((InternalEList<?>) getDataInputAssociations()).basicRemove(otherEnd, msgs); case Bpmn2Package.ACTIVITY__DATA_OUTPUT_ASSOCIATIONS: return ((InternalEList<?>) getDataOutputAssociations()).basicRemove(otherEnd, msgs); case Bpmn2Package.ACTIVITY__RESOURCES: return ((InternalEList<?>) getResources()).basicRemove(otherEnd, msgs); case Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS: return basicSetLoopCharacteristics(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bpmn2Package.ACTIVITY__IO_SPECIFICATION: return getIoSpecification(); case Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS: return getBoundaryEventRefs(); case Bpmn2Package.ACTIVITY__PROPERTIES: return getProperties(); case Bpmn2Package.ACTIVITY__DATA_INPUT_ASSOCIATIONS: return getDataInputAssociations(); case Bpmn2Package.ACTIVITY__DATA_OUTPUT_ASSOCIATIONS: return getDataOutputAssociations(); case Bpmn2Package.ACTIVITY__RESOURCES: return getResources(); case Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS: return getLoopCharacteristics(); case Bpmn2Package.ACTIVITY__COMPLETION_QUANTITY: return getCompletionQuantity(); case Bpmn2Package.ACTIVITY__DEFAULT: return getDefault(); case Bpmn2Package.ACTIVITY__IS_FOR_COMPENSATION: return isIsForCompensation(); case Bpmn2Package.ACTIVITY__START_QUANTITY: return getStartQuantity(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bpmn2Package.ACTIVITY__IO_SPECIFICATION: setIoSpecification((InputOutputSpecification) newValue); return; case Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS: getBoundaryEventRefs().clear(); getBoundaryEventRefs().addAll((Collection<? extends BoundaryEvent>) newValue); return; case Bpmn2Package.ACTIVITY__PROPERTIES: getProperties().clear(); getProperties().addAll((Collection<? extends Property>) newValue); return; case Bpmn2Package.ACTIVITY__DATA_INPUT_ASSOCIATIONS: getDataInputAssociations().clear(); getDataInputAssociations().addAll((Collection<? extends DataInputAssociation>) newValue); return; case Bpmn2Package.ACTIVITY__DATA_OUTPUT_ASSOCIATIONS: getDataOutputAssociations().clear(); getDataOutputAssociations().addAll((Collection<? extends DataOutputAssociation>) newValue); return; case Bpmn2Package.ACTIVITY__RESOURCES: getResources().clear(); getResources().addAll((Collection<? extends ResourceRole>) newValue); return; case Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS: setLoopCharacteristics((LoopCharacteristics) newValue); return; case Bpmn2Package.ACTIVITY__COMPLETION_QUANTITY: setCompletionQuantity((Integer) newValue); return; case Bpmn2Package.ACTIVITY__DEFAULT: setDefault((SequenceFlow) newValue); return; case Bpmn2Package.ACTIVITY__IS_FOR_COMPENSATION: setIsForCompensation((Boolean) newValue); return; case Bpmn2Package.ACTIVITY__START_QUANTITY: setStartQuantity((Integer) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bpmn2Package.ACTIVITY__IO_SPECIFICATION: setIoSpecification((InputOutputSpecification) null); return; case Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS: getBoundaryEventRefs().clear(); return; case Bpmn2Package.ACTIVITY__PROPERTIES: getProperties().clear(); return; case Bpmn2Package.ACTIVITY__DATA_INPUT_ASSOCIATIONS: getDataInputAssociations().clear(); return; case Bpmn2Package.ACTIVITY__DATA_OUTPUT_ASSOCIATIONS: getDataOutputAssociations().clear(); return; case Bpmn2Package.ACTIVITY__RESOURCES: getResources().clear(); return; case Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS: setLoopCharacteristics((LoopCharacteristics) null); return; case Bpmn2Package.ACTIVITY__COMPLETION_QUANTITY: setCompletionQuantity(COMPLETION_QUANTITY_EDEFAULT); return; case Bpmn2Package.ACTIVITY__DEFAULT: setDefault((SequenceFlow) null); return; case Bpmn2Package.ACTIVITY__IS_FOR_COMPENSATION: setIsForCompensation(IS_FOR_COMPENSATION_EDEFAULT); return; case Bpmn2Package.ACTIVITY__START_QUANTITY: setStartQuantity(START_QUANTITY_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bpmn2Package.ACTIVITY__IO_SPECIFICATION: return ioSpecification != null; case Bpmn2Package.ACTIVITY__BOUNDARY_EVENT_REFS: return boundaryEventRefs != null && !boundaryEventRefs.isEmpty(); case Bpmn2Package.ACTIVITY__PROPERTIES: return properties != null && !properties.isEmpty(); case Bpmn2Package.ACTIVITY__DATA_INPUT_ASSOCIATIONS: return dataInputAssociations != null && !dataInputAssociations.isEmpty(); case Bpmn2Package.ACTIVITY__DATA_OUTPUT_ASSOCIATIONS: return dataOutputAssociations != null && !dataOutputAssociations.isEmpty(); case Bpmn2Package.ACTIVITY__RESOURCES: return resources != null && !resources.isEmpty(); case Bpmn2Package.ACTIVITY__LOOP_CHARACTERISTICS: return loopCharacteristics != null; case Bpmn2Package.ACTIVITY__COMPLETION_QUANTITY: return completionQuantity != COMPLETION_QUANTITY_EDEFAULT; case Bpmn2Package.ACTIVITY__DEFAULT: return default_ != null; case Bpmn2Package.ACTIVITY__IS_FOR_COMPENSATION: return isForCompensation != IS_FOR_COMPENSATION_EDEFAULT; case Bpmn2Package.ACTIVITY__START_QUANTITY: return startQuantity != START_QUANTITY_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (completionQuantity: "); result.append(completionQuantity); result.append(", isForCompensation: "); result.append(isForCompensation); result.append(", startQuantity: "); result.append(startQuantity); result.append(')'); return result.toString(); } // BPMN2.0 /** * * * @return */ public SkipStrategy getSkipStrategy() { SkipStrategy skipStrategy = EMFExtensionUtil.getSkipStrategy(this); return skipStrategy; } /** * * @param executionContext * @throws Exception */ public void enter(ExecutionContext executionContext) { TokenEntity token = executionContext.getToken(); token.setFlowNode(this); // fireEvent(BaseElementEvent.EVENTTYPE_NODE_ENTER, executionContext); token.setNodeEnterTime(new Date()); executionContext.setSequenceFlow(null); executionContext.setGroupID(null); executionContext.setSequenceFlowSource(null); SkipStrategy skipStrategy = getSkipStrategy(); // entryList.get(0); if (skipStrategy != null) { boolean isEnable = skipStrategy.isIsEnable(); if (isEnable) { boolean valueObj = false; if (skipStrategy.getExpression() != null) { String expressionValue = skipStrategy.getExpression().getValue(); if (expressionValue != null && !expressionValue.equals("")) { try { valueObj = StringUtil.getBoolean(ExpressionMgmt.execute(expressionValue, executionContext)); } catch (Exception e) { throw new FixFlowException(" " + this.getId() + " " + this.getName() + " ", e); } } } if (valueObj) { boolean isCreateSkipProcess = skipStrategy.isIsCreateSkipProcess(); if (isCreateSkipProcess) { executionContext.setSkipStrategy(skipStrategy); skipExecute(executionContext); } else { } super.leave(executionContext); return; } } } eventExecute(executionContext); } private void tokenEnter(ExecutionContext executionContext) { //TokenEntity token = executionContext.getToken(); //token.setFlowNode(this); fireEvent(BaseElementEvent.EVENTTYPE_NODE_ENTER, executionContext); //token.setNodeEnterTime(new Date()); //executionContext.setSequenceFlow(null); //executionContext.setSequenceFlowSource(null); execute(executionContext); /* if (this instanceof Activity && ((Activity) this).getLoopCharacteristics() != null) { loopExecute(executionContext); } else { }*/ } private void forkedTokenEnter(ExecutionContext executionContext) { TokenEntity token = executionContext.getToken(); token.setFlowNode(this); //fireEvent(BaseElementEvent.EVENTTYPE_NODE_ENTER, executionContext); token.setNodeEnterTime(new Date()); executionContext.setSequenceFlow(null); executionContext.setSequenceFlowSource(null); loopExecute(executionContext); /* if (this instanceof Activity && ((Activity) this).getLoopCharacteristics() != null) { loopExecute(executionContext); } else { }*/ } protected void eventExecute(ExecutionContext executionContext) { //fireEvent(BaseElementEvent.EVENTTYPE_NODE_ENTER, executionContext); if (this.getBoundaryEventRefs().size() > 0) { List<BoundaryEvent> boundaryEvents = this.getBoundaryEventRefs(); TokenEntity tokenEntity = executionContext.getToken(); String nodeTokenId = this.getId(); TokenEntity nodeToken = this.createForkedToken(tokenEntity, nodeTokenId).token; ExecutionContext nodeChildExecutionContext = ProcessObjectFactory.FACTORYINSTANCE.createExecutionContext(nodeToken); this.forkedTokenEnter(nodeChildExecutionContext); for (BoundaryEvent boundaryEvent : boundaryEvents) { // String tokenId = boundaryEvent.getId(); // TokenEntity childToken =this.createForkedToken(tokenEntity, // tokenId).token; // ExecutionContext childExecutionContext = // ProcessObjectFactory.FACTORYINSTANCE.createExecutionContext(childToken); // token BoundaryEvent boundaryEvent.execute(executionContext); } // execute(executionContext); } else { loopExecute(executionContext); } } protected void skipExecute(ExecutionContext executionContext) { // debugLog.debug(" "+getId()+" !"); } @SuppressWarnings("rawtypes") protected void loopExecute(ExecutionContext executionContext) { Activity activity = (Activity) this; LoopCharacteristics loopCharacteristics = activity.getLoopCharacteristics(); if (loopCharacteristics instanceof MultiInstanceLoopCharacteristics) { // BUG List<FeatureMap.Entry> dataOutputentryList = EMFExtensionUtil.getExtensionElements(loopCharacteristics, "loopDataOutputCollection"); if (dataOutputentryList == null || dataOutputentryList.size() == 0) { } else { dataOutputentryList.get(0); // loopDataOutputCollection outputDataItem completionCondition FeatureMap.Entry dataOutputexpressionEntry = EMFExtensionUtil.getExtensionElementsInEntry(dataOutputentryList.get(0), "expression") .get(0); String dataOutputexpressionValue = EMFExtensionUtil.getExtensionElementValue(dataOutputexpressionEntry); if (dataOutputexpressionValue != null && !dataOutputexpressionValue.equals("")) { Object valueObj = ExpressionMgmt.execute(dataOutputexpressionValue, executionContext); if (valueObj != null) { if (valueObj instanceof Collection) { ((Collection) valueObj).clear(); } else { throw new FixFlowException(""); } } } } List<FeatureMap.Entry> entryList = EMFExtensionUtil.getExtensionElements(loopCharacteristics, "LoopDataInputCollection"); // entryList.get(0); FeatureMap.Entry expressionEntry = EMFExtensionUtil.getExtensionElementsInEntry(entryList.get(0), "expression").get(0); String expressionValue = EMFExtensionUtil.getExtensionElementValue(expressionEntry); if (expressionValue != null && !expressionValue.equals("")) { String groupID = GuidUtil.CreateGuid(); executionContext.setGroupID(groupID); Object valueObj = ExpressionMgmt.execute(expressionValue, executionContext); if (valueObj != null) { if (valueObj instanceof Collection) { Collection<?> valueObjCollection = (Collection<?>) valueObj; if (valueObjCollection.size() == 0) { throw new FixFlowException("0,"); } for (Object object : valueObjCollection) { MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = (MultiInstanceLoopCharacteristics) loopCharacteristics; FeatureMap.Entry expressionEntryTemp = EMFExtensionUtil.getExtensionElements( multiInstanceLoopCharacteristics.getInputDataItem(), "expression").get(0); String expressionValueTemp = EMFExtensionUtil.getExtensionElementValue(expressionEntryTemp); ExpressionMgmt.setVariable(expressionValueTemp, object, executionContext); this.tokenEnter(executionContext); } } else { if (valueObj instanceof String[]) { String[] valueObjString = (String[]) valueObj; for (int i = 0; i < valueObjString.length; i++) { MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = (MultiInstanceLoopCharacteristics) loopCharacteristics; FeatureMap.Entry expressionEntryTemp = EMFExtensionUtil.getExtensionElements( multiInstanceLoopCharacteristics.getInputDataItem(), "expression").get(0); String expressionValueTemp = EMFExtensionUtil.getExtensionElementValue(expressionEntryTemp); ExpressionMgmt.setVariable(expressionValueTemp, valueObjString[i], executionContext); this.tokenEnter(executionContext); } } else { if (valueObj != null && !valueObj.equals("")) { String[] valueObjString = valueObj.toString().split(","); if (valueObjString.length > 0) { for (int i = 0; i < valueObjString.length; i++) { MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = (MultiInstanceLoopCharacteristics) loopCharacteristics; FeatureMap.Entry expressionEntryTemp = EMFExtensionUtil.getExtensionElements( multiInstanceLoopCharacteristics.getInputDataItem(), "expression").get(0); String expressionValueTemp = EMFExtensionUtil.getExtensionElementValue(expressionEntryTemp); ExpressionMgmt.setVariable(expressionValueTemp, valueObjString[i], executionContext); this.tokenEnter(executionContext); } } else { throw new FixFlowException("."); } } else { throw new FixFlowException("."); } } } } else { throw new FixFlowException("!"); } } else { throw new FixFlowException("!"); } } else { if(loopCharacteristics instanceof StandardLoopCharacteristics){ tokenEnter(executionContext); }else{ tokenEnter(executionContext); } } } @SuppressWarnings({ "unchecked" }) public void leave(ExecutionContext executionContext) { if (this instanceof Activity && ((Activity) this).getLoopCharacteristics() != null) { Activity activity = (Activity) this; LoopCharacteristics loopCharacteristics = activity.getLoopCharacteristics(); if (loopCharacteristics instanceof MultiInstanceLoopCharacteristics) { List<FeatureMap.Entry> entryList = EMFExtensionUtil.getExtensionElements(loopCharacteristics, "loopDataOutputCollection"); if (entryList != null && entryList.size() > 0) { entryList.get(0); // loopDataOutputCollection outputDataItem // completionCondition FeatureMap.Entry expressionEntry = EMFExtensionUtil.getExtensionElementsInEntry(entryList.get(0), "expression").get(0); String expressionValue = EMFExtensionUtil.getExtensionElementValue(expressionEntry); if (expressionValue != null && !expressionValue.equals("")) { Object valueObj = ExpressionMgmt.execute(expressionValue, executionContext); if (valueObj != null) { if (valueObj instanceof Collection) { MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = (MultiInstanceLoopCharacteristics) loopCharacteristics; FeatureMap.Entry expressionEntryTemp = EMFExtensionUtil.getExtensionElements( multiInstanceLoopCharacteristics.getOutputDataItem(), "expression").get(0); String expressionValueTemp = EMFExtensionUtil.getExtensionElementValue(expressionEntryTemp); @SuppressWarnings("rawtypes") Collection collection = (Collection) valueObj; collection.add(ExpressionMgmt.execute(expressionValueTemp, executionContext)); } } } } else { } MultiInstanceLoopCharacteristics multiInstanceLoopCharacteristics = (MultiInstanceLoopCharacteristics) loopCharacteristics; FormalExpression formalExpression = (FormalExpression) multiInstanceLoopCharacteristics.getCompletionCondition(); if (formalExpression == null || formalExpression.getBody() == null || formalExpression.getBody().equals("")) { throw new FixFlowException("."); } else { String evalue = formalExpression.getBody(); if (StringUtil.getBoolean(ExpressionMgmt.execute(evalue, executionContext))) { super.leave(executionContext); } } } else { throw new FixFlowException(""); } } else { super.leave(executionContext); } } public void leaveClearData(ExecutionContext executionContext) { TokenEntity tokenEntity = executionContext.getToken(); if (this.getBoundaryEventRefs().size() > 0) { String parentTokenId = tokenEntity.getParent().getId(); try { Scheduler scheduler = Context.getProcessEngineConfiguration().getSchedulerFactory().getScheduler(); scheduler.deleteJob(JobKey.jobKey(tokenEntity.getParent().getId(), "FixTimeOutTask_" + parentTokenId)); } catch (SchedulerException e) { e.printStackTrace(); throw new FixFlowException(" " + this.getId() + " ! : " + e.toString(), e); } } } public void boundaryEventExecute() { } } // ActivityImpl
package org.zkoss.ganttz; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.Date; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.zkoss.ganttz.adapters.IDisabilityConfiguration; import org.zkoss.ganttz.data.Milestone; import org.zkoss.ganttz.data.Task; import org.zkoss.ganttz.data.Task.IReloadResourcesTextRequested; import org.zkoss.ganttz.data.TaskContainer; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.constraint.Constraint.IConstraintViolationListener; import org.zkoss.json.JSONArray; import org.zkoss.lang.Objects; import org.zkoss.zk.au.AuRequest; import org.zkoss.zk.au.AuService; import org.zkoss.zk.au.out.AuInvoke; import org.zkoss.zk.mesg.MZk; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.ext.AfterCompose; import org.zkoss.zk.ui.sys.ContentRenderer; import org.zkoss.zul.Div; public class TaskComponent extends Div implements AfterCompose { private static final Log LOG = LogFactory.getLog(TaskComponent.class); private static final int HEIGHT_PER_TASK = 10; private static final int CONSOLIDATED_MARK_HALF_WIDTH = 3; private static Pattern pixelsSpecificationPattern = Pattern .compile("\\s*(\\d+)px\\s*;?\\s*"); protected final IDisabilityConfiguration disabilityConfiguration; private PropertyChangeListener criticalPathPropertyListener; public static TaskComponent asTaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration, boolean isTopLevel) { final TaskComponent result; if (task.isContainer()) { result = TaskContainerComponent.asTask((TaskContainer) task, disabilityConfiguration); } else if (task instanceof Milestone) { result = new MilestoneComponent(task, disabilityConfiguration); } else { result = new TaskComponent(task, disabilityConfiguration); } result.isTopLevel = isTopLevel; return TaskRow.wrapInRow(result); } public static TaskComponent asTaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration) { return asTaskComponent(task, disabilityConfiguration, true); } private IReloadResourcesTextRequested reloadResourcesTextRequested; public TaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration) { setHeight(HEIGHT_PER_TASK + "px"); setContext("idContextMenuTaskAssignment"); this.task = task; setClass(calculateCSSClass()); setId(UUID.randomUUID().toString()); this.disabilityConfiguration = disabilityConfiguration; taskViolationListener = new IConstraintViolationListener<Date>() { @Override public void constraintViolated(Constraint<Date> constraint, Date value) { // TODO mark graphically task as violated } }; this.task.addConstraintViolationListener(taskViolationListener); reloadResourcesTextRequested = new IReloadResourcesTextRequested() { @Override public void reloadResourcesTextRequested() { if (canShowResourcesText()) { smartUpdate("resourcesText", getResourcesText()); } String cssClass = calculateCSSClass(); response("setClass", new AuInvoke(TaskComponent.this, "setClass", cssClass)); // FIXME: Refactorize to another listener updateDeadline(); } }; this.task.addReloadListener(reloadResourcesTextRequested); setAuService(new AuService(){ public boolean service(AuRequest request, boolean everError){ String command = request.getCommand(); final TaskComponent ta; String[] requestData; if (command.equals("onUpdatePosition")){ ta = retrieveTaskComponent(request); requestData = retrieveData(request, 2); ta.doUpdatePosition(requestData[0], requestData[1]); Events.postEvent(new Event(getId(), ta, request.getData())); return true; } if (command.equals("onUpdateWidth")){ ta = retrieveTaskComponent(request); requestData = retrieveData(request, 1); ta.doUpdateSize(requestData[0]); Events.postEvent(new Event(getId(), ta, request.getData())); return true; } if (command.equals("onAddDependency")){ ta = retrieveTaskComponent(request); requestData = retrieveData(request, 1); ta.doAddDependency(requestData[0]); Events.postEvent(new Event(getId(), ta, request.getData())); return true; } return false; } private TaskComponent retrieveTaskComponent(AuRequest request){ final TaskComponent ta = (TaskComponent) request.getComponent(); if (ta == null) { throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED, this); } return ta; } private String[] retrieveData(AuRequest request, int requestLength){ String [] requestData = (String[]) ((JSONArray)request.getData().get("")).toArray(new String[requestLength]); if (requestData == null || requestData.length != requestLength) { throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA, new Object[] { Objects.toString(requestData), this }); } return requestData; } }); } /* Generate CSS class attribute depending on task properties */ protected String calculateCSSClass() { String cssClass = isSubcontracted() ? "box subcontracted-task" : "box standard-task"; cssClass += isResizingTasksEnabled() ? " yui-resize" : ""; if (isContainer()) { cssClass += task.isExpanded() ? " expanded" : " closed "; } cssClass += task.isInCriticalPath() ? " critical" : ""; cssClass += " " + task.getAssignedStatus(); if (task.isLimiting()) { cssClass += task.isLimitingAndHasDayAssignments() ? " limiting-assigned " : " limiting-unassigned "; } return cssClass; } protected void updateClass() { response(null, new AuInvoke(this, "setClass", new Object[] { calculateCSSClass() })); } public final void afterCompose() { updateProperties(); if (propertiesListener == null) { propertiesListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (isInPage()) { updateProperties(); } } }; } this.task .addFundamentalPropertiesChangeListener(propertiesListener); if (criticalPathPropertyListener == null) { criticalPathPropertyListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateClass(); } }; } this.task .addCriticalPathPropertyChangeListener(criticalPathPropertyListener); updateClass(); } /** * Note: This method is intended to be overridden. */ protected boolean canShowResourcesText() { return true; } private String _color; private boolean isTopLevel; private final Task task; private transient PropertyChangeListener propertiesListener; private IConstraintViolationListener<Date> taskViolationListener; public TaskRow getRow() { if (getParent() == null) { throw new IllegalStateException( "the TaskComponent should have been wraped by a " + TaskRow.class.getName()); } return (TaskRow) getParent(); } public Task getTask() { return task; } public String getTaskName() { return task.getName(); } public String getLength() { return null; } public boolean isResizingTasksEnabled() { return (disabilityConfiguration != null) && disabilityConfiguration.isResizingTasksEnabled() && !task.isSubcontracted() && task.canBeExplicitlyResized(); } public boolean isMovingTasksEnabled() { return (disabilityConfiguration != null) && disabilityConfiguration.isMovingTasksEnabled() && task.canBeExplicitlyMoved(); } void doUpdatePosition(String leftX, String topY) { Date startBeforeMoving = this.task.getBeginDate(); this.task.moveTo(getMapper().toDate(Integer.parseInt(leftX))); boolean remainsInOriginalPosition = this.task.getBeginDate().equals( startBeforeMoving); if (remainsInOriginalPosition) { updateProperties(); } } void doUpdateSize(String size) { this.task.setLengthMilliseconds(getMapper().toMilliseconds(Integer.parseInt(size))); updateWidth(); } void doAddDependency(String destinyTaskId) { getTaskList().addDependency(this, ((TaskComponent) getFellow(destinyTaskId))); } public String getColor() { return _color; } public void setColor(String color) { if ((color != null) && (color.length() == 0)) { color = null; } if (!Objects.equals(_color, color)) { _color = color; } } /* * We override the method of renderProperties to put the color property as part * of the style */ protected void renderProperties(ContentRenderer renderer) throws IOException{ if(getColor() != null) setStyle("background-color : " + getColor()); setWidgetAttribute("movingTasksEnabled",((Boolean)isMovingTasksEnabled()).toString()); setWidgetAttribute("resizingTasksEnabled", ((Boolean)isResizingTasksEnabled()).toString()); /*We can't use setStyle because of restrictions * involved with UiVisualizer#getResponses and the * smartUpdate method (when the request is asynchronous) */ render(renderer, "style", "position : absolute"); render(renderer, "_labelsText", getLabelsText()); render(renderer, "_resourcesText", getResourcesText()); render(renderer, "_tooltipText", getTooltipText()); super.renderProperties(renderer); } /* * We send a response to the client to create the arrow we are going to use * to create the dependency */ public void addDependency() { response("depkey", new AuInvoke(this, "addDependency")); } private IDatesMapper getMapper() { return getTaskList().getMapper(); } public TaskList getTaskList() { return getRow().getTaskList(); } @Override public void setParent(Component parent) { Validate.isTrue(parent == null || parent instanceof TaskRow); super.setParent(parent); } public final void zoomChanged() { updateProperties(); } public void updateProperties() { if (!isInPage()) { return; } setLeft("0"); setLeft(getMapper().toPixels(this.task.getBeginDate()) + "px"); updateWidth(); smartUpdate("name", this.task.getName()); DependencyList dependencyList = getDependencyList(); if (dependencyList != null) { dependencyList.redrawDependenciesConnectedTo(this); } updateDeadline(); updateCompletionIfPossible(); updateClass(); } private void updateWidth() { setWidth("0"); setWidth(getMapper().toPixels(this.task.getLengthMilliseconds()) + "px"); } private void updateDeadline() { if (task.getDeadline() != null) { String position = getMapper().toPixels(task.getDeadline()) + "px"; response(null, new AuInvoke(this, "moveDeadline", position)); } else { // Move deadline out of visible area response(null, new AuInvoke(this, "moveDeadline","-100px")); } if (task.getConsolidatedline() != null) { String position = (getMapper().toPixels(task.getConsolidatedline()) - CONSOLIDATED_MARK_HALF_WIDTH) + "px"; response(null, new AuInvoke(this, "moveConsolidatedline", position)); } else { // Move consolidated line out of visible area response(null, new AuInvoke(this, "moveConsolidatedline", "-100px")); } } public void updateCompletionIfPossible() { try { updateCompletion(); } catch (Exception e) { LOG.error("failure at updating completion", e); } } private void updateCompletion() { long beginMilliseconds = this.task.getBeginDate().getTime(); long hoursAdvanceEndMilliseconds = this.task.getHoursAdvanceEndDate() .getTime() - beginMilliseconds; if (hoursAdvanceEndMilliseconds < 0) { hoursAdvanceEndMilliseconds = 0; } String widthHoursAdvancePercentage = getMapper().toPixels( hoursAdvanceEndMilliseconds) + "px"; response(null, new AuInvoke(this, "resizeCompletionAdvance", widthHoursAdvancePercentage)); long advanceEndMilliseconds = this.task.getAdvanceEndDate() .getTime() - beginMilliseconds; if (advanceEndMilliseconds < 0) { advanceEndMilliseconds = 0; } String widthAdvancePercentage = getMapper().toPixels( advanceEndMilliseconds) + "px"; response(null, new AuInvoke(this, "resizeCompletion2Advance", widthAdvancePercentage)); } public void updateTooltipText() { smartUpdate("taskTooltipText", task.updateTooltipText()); } private DependencyList getDependencyList() { return getGanntPanel().getDependencyList(); } private GanttPanel getGanntPanel() { return getTaskList().getGanttPanel(); } private boolean isInPage() { return getPage() != null; } void publishTaskComponents(Map<Task, TaskComponent> resultAccumulated) { resultAccumulated.put(getTask(), this); publishDescendants(resultAccumulated); } protected void publishDescendants(Map<Task, TaskComponent> resultAccumulated) { } protected void remove() { this.getRow().detach(); task.removeReloadListener(reloadResourcesTextRequested); } public boolean isTopLevel() { return isTopLevel; } public String getTooltipText() { return task.getTooltipText(); } public String getLabelsText() { return task.getLabelsText(); } public String getLabelsDisplay() { Planner planner = getTaskList().getGanttPanel().getPlanner(); return planner.isShowingLabels() ? "inline" : "none"; } public String getResourcesText() { return task.getResourcesText(); } public String getResourcesDisplay() { Planner planner = getTaskList().getGanttPanel().getPlanner(); return planner.isShowingResources() ? "inline" : "none"; } public boolean isSubcontracted() { return task.isSubcontracted(); } public boolean isContainer() { return task.isContainer(); } @Override public String toString() { return task.toString(); } }
package gobblin.writer; import com.google.common.base.Optional; import gobblin.configuration.ConfigurationKeys; import gobblin.configuration.State; import gobblin.source.extractor.schema.Schema; import gobblin.util.ForkOperatorUtils; import gobblin.util.WriterUtils; import org.apache.avro.file.CodecFactory; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.parquet.example.data.Group; import org.apache.parquet.hadoop.ParquetWriter; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.conf.Configuration; import org.apache.parquet.schema.MessageType; import org.apache.parquet.avro.*; import org.apache.hadoop.fs.Path; class ParquetHdfsDataWriter extends FsDataWriter<GenericRecord>{ protected final AtomicLong count = new AtomicLong(0); private MessageType schema = null; private ParquetWriter writer; public ParquetHdfsDataWriter(State properties, String fileName, org.apache.avro.Schema schema, int numBranches, int branchId) throws IOException { super(properties, fileName, numBranches, branchId); // CodecFactory codecFactory = // WriterUtils.getCodecFactory(Optional.fromNullable(properties.getProp( // ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_CODEC_TYPE, numBranches, branchId))), // Optional.fromNullable(properties.getProp(ForkOperatorUtils // .getPropertyNameForBranch(ConfigurationKeys.WRITER_DEFLATE_LEVEL, numBranches, branchId)))); // this.schema = schema; // this.groupWriter = new GenericDatumWriter<Group>(); this.writer = this.closer.register(createDataFileWriter(fileName, schema)); } @Override public void write(GenericRecord record) throws IOException { // try { writer.write(record); // } catch (InterruptedException e) { // throw new IOException(e); this.count.incrementAndGet(); } @Override public long recordsWritten() { return this.count.get(); } @Override public long bytesWritten() throws IOException { if (!this.fs.exists(this.outputFile)) { return 0; } return this.fs.getFileStatus(this.outputFile).getLen(); } private ParquetWriter<GenericRecord> createDataFileWriter(String fileName, org.apache.avro.Schema schema ) throws IOException { // DataFileWriter<GenericRecord> writer = new DataFileWriter<GenericRecord>(this.datumWriter); // writer.setCodec(codecFactory); Configuration testConf = new Configuration(); testConf.setBoolean(AvroReadSupport.AVRO_COMPATIBILITY, true); testConf.setBoolean("parquet.avro.add-list-element-records", false); testConf.setBoolean("parquet.avro.write-old-list-structure", false); System.out.println("fffffffffffffffffffffffffffffffffffileNeme OUTPUT: " + fileName); return AvroParquetWriter .<GenericRecord>builder(new Path(fileName)) // .<GenericRecord>builder(this.stagingFile) .withSchema(schema) .withConf(testConf) .build(); // return new ParquetWriter<GenericRecord>(file,new GroupWriteSupport(schema)); // Open the file and return the DataFileWriter // return writer.create(this.schema, this.stagingFileOutputStream); } }
package MWC.TacticalData; import java.awt.Color; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.util.Date; import MWC.GUI.Editable; import MWC.GUI.ExcludeFromRightClickEdit; import MWC.GUI.FireExtended; import MWC.GUI.FireReformatted; import MWC.GUI.Plottable; import MWC.GenericData.HiResDate; import MWC.Utilities.TextFormatting.DebriefFormatDateTime; public final class NarrativeEntry implements MWC.GUI.Plottable, Serializable, ExcludeFromRightClickEdit { public static final String DTG = "DTG"; // member variables private String _track; private HiResDate _DTG; private String _entry; private String _type; String _DTGString = null; private transient NarrativeEntryInfo _myInfo; private Color _color = Color.white; private static final long serialVersionUID = 1L; // constructor /** * new constructor - for narrative entries which include the type of entry * (typically for SMNT narratives) * * @param track * name of the track this applies to * @param type * what sort of entry this is (or null) * @param DTG * when the entry was recorded * @param entry * the content of the entry */ public NarrativeEntry(final String track, final String type, final HiResDate DTG, final String entry) { _track = track; _DTG = DTG; _entry = entry; _type = type; } /** * old constructor - for when narratives didn't include the type attribute * * @param track * name of the track this applies to * @param DTG * when the entry was recorded * @param entry * the content of the entry */ public NarrativeEntry(final String track, final HiResDate DTG, final String entry) { this(track, null, DTG, entry); } // accessor methods public final String getTrackName() { return _track; } public final String getSource() { return _track; } @FireReformatted public final void setSource(final String track) { _track = track; } public final String getEntry() { return _entry; } @FireReformatted public void setEntry(final String val) { _entry = val; } public final HiResDate getDTG() { return _DTG; } @FireExtended public void setDTG(final HiResDate date) { _DTG = date; } public final String getType() { return _type; } @FireReformatted public void setType(final String type) { _type = type; } public final String getDTGString() { if (_DTGString == null) _DTGString = DebriefFormatDateTime.toStringHiRes(_DTG); return _DTGString; } public void setColor(Color color) { _color = color; } public Color getColor() { return _color; } /** * member function to meet requirements of comparable interface * */ public final int compareTo(final Plottable o) { final NarrativeEntry other = (NarrativeEntry) o; int result = _DTG.compareTo(other._DTG); if (result == 0) result = 1; return result; } // member methods to meet requirements of Plottable interface /** * paint this object to the specified canvas */ public final void paint(final MWC.GUI.CanvasType dest) { } /** * find the data area occupied by this item */ public final MWC.GenericData.WorldArea getBounds() { return null; } /** * it this item currently visible? */ public final boolean getVisible() { return true; } /** * set the visibility (although we ignore this) */ public final void setVisible(final boolean val) { } /** * how far away are we from this point? or return null if it can't be * calculated */ public final double rangeFrom(final MWC.GenericData.WorldLocation other) { return -1; } /** * get the editor for this item * * @return the BeanInfo data for this editable object */ public final MWC.GUI.Editable.EditorType getInfo() { if (_myInfo == null) _myInfo = new NarrativeEntryInfo(this, this.toString()); return _myInfo; } /** * whether there is any edit information for this item this is a convenience * function to save creating the EditorType data first * * @return yes/no */ public final boolean hasEditor() { return true; } /** * get the name of this entry, using the formatted DTG */ public final String getName() { return DebriefFormatDateTime.toStringHiRes(_DTG); } public final String toString() { return getName(); } public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof NarrativeEntry)) return false; return super.equals(obj); } // bean info for this class public final class NarrativeEntryInfo extends Editable.EditorType { public NarrativeEntryInfo(final NarrativeEntry data, final String theName) { super(data, theName, data.toString()); } public final PropertyDescriptor[] getPropertyDescriptors() { try { final PropertyDescriptor[] myRes = { prop("Type", "the type of entry", FORMAT), prop("Source", "the source for this entry", FORMAT), prop(DTG, "the time this entry was recorded", FORMAT), prop("Color", "the color for this narrative entry", FORMAT), prop("Entry", "the content of this entry", FORMAT), }; return myRes; } catch (final IntrospectionException e) { e.printStackTrace(); return super.getPropertyDescriptors(); } } } // testing for this class static public final class testMe extends junit.framework.TestCase { static public final String TEST_ALL_TEST_TYPE = "UNIT"; public testMe(final String val) { super(val); } public final void testMyParams() { final HiResDate hd = new HiResDate(new Date()); final NarrativeEntry ne = new NarrativeEntry("aaa", "bbb", hd, "vvvv"); editableTesterSupport.testParams(ne, this); } } }
package net.lucenews.controller; import java.util.*; import javax.xml.parsers.*; import net.lucenews.*; import net.lucenews.atom.*; import net.lucenews.model.*; import net.lucenews.model.exception.*; import org.apache.lucene.document.Field; import org.w3c.dom.*; public class XOXOController { /** * Transforms a set of properties into an XOXO-formatted * &lt;dt&gt; list. * * @param properties The properties to transform * @param document The DOM document used to generate elements * @return An XOXO-formatted &lt;dl&gt; element */ public static Element asElement (Properties properties, Document document) { Element dl = document.createElement( "dl" ); dl.setAttribute( "class", "xoxo" ); Enumeration names = properties.propertyNames(); while( names.hasMoreElements() ) { String name = (String) names.nextElement(); String value = properties.getProperty( name ); Element dt = document.createElement( "dt" ); dt.appendChild( document.createTextNode( String.valueOf( name ) ) ); dl.appendChild( dt ); Element dd = document.createElement( "dd" ); dd.appendChild( document.createTextNode( String.valueOf( value ) ) ); dl.appendChild( dd ); } return dl; } /** * Transforms the given document into an XOXO-formatted * &lt;dl&gt; list. * * @param luceneDocument The document to be transformed * @param document the DOM document used to create elements * @return An XOXO-formatted &lt;dl&gt; element */ public static Element asElement (LuceneDocument luceneDocument, Document document) { Element dl = document.createElement( "dl" ); dl.setAttribute( "class", "xoxo" ); if (luceneDocument == null) return dl; Enumeration<Field> fields = luceneDocument.fields(); while( fields.hasMoreElements() ) { Field field = fields.nextElement(); String name = field.name(); String value = field.stringValue(); Element dt = document.createElement( "dt" ); String className = getClassName( field ); if( className.length() > 0 ) dt.setAttribute( "class", className ); dt.appendChild( document.createTextNode( String.valueOf( name ) ) ); dl.appendChild( dt ); Element dd = document.createElement( "dd" ); dd.appendChild( document.createTextNode( String.valueOf( value ) ) ); dl.appendChild( dd ); } return dl; } /** * Determines the appropriate class name for a given field. * * @param field The field in question * @return The appropriate class name for the given field */ public static String getClassName (Field field) { StringBuffer classBuffer = new StringBuffer(); if( field.isStored() ) classBuffer.append( " stored" ); if( field.isIndexed() ) classBuffer.append( " indexed" ); if( field.isTokenized() ) classBuffer.append( " tokenized" ); if( field.isTermVectorStored() ) classBuffer.append( " termvectorstored" ); return String.valueOf( classBuffer ).trim(); } /** * Transforms the given Atom entry into an XOXO-formatted * &lt;dl&gt; list element. This is typically accomplished by * examining the entry's content. * * @param entry The Atom entry to transform * @return An XOXO-formatted &lt;dl&gt; list element. */ public static Element asElement (Entry entry) throws LuceneException { Content content = entry.getContent(); if( content == null ) throw new LuceneException( "Entry contains no content", LuceneResponse.SC_BAD_REQUEST ); if( content instanceof NodeContent ) { NodeContent nodeContent = (NodeContent) content; Node[] nodes = nodeContent.getNodes(); for( int i = 0; i < nodes.length; i++ ) { Node node = nodes[ i ]; if( node.getNodeType() == Node.ELEMENT_NODE ) { Element dl = (Element) ( (Element) node ).getElementsByTagName( "dl" ).item( 0 ); return dl; } } } if( content instanceof TextContent ) { TextContent textContent = (TextContent) content; if( textContent.isType("xhtml") ) { try { return (Element) textContent.asDocument().getElementsByTagName( "dl" ).item( 0 ); } catch(Exception e) { e.printStackTrace(); } } } return null; } /** * Transforms a given Atom entry into an array * of fields. * * @param entry The Atom entry to transform * @return An array of fields * @throws LuceneException */ public static Field[] asFields (Entry entry) throws LuceneException { return asFields( asElement( entry ) ); } /** * Transforms a given Atom entry into a set * of properties. * * @param entry The Atom entry to transform * @return A set of properties * @throws LuceneException */ public static Properties asProperties (Entry entry) throws LuceneException { return asProperties( asElement( entry ) ); } /** * Transforms the given properties into an Atom content * object. * * @param properties The properties to be transformed * @return An Atom content object containing the properties * @throws ParserConfigurationException */ public static Content asContent (Properties properties) throws ParserConfigurationException { Document document = XMLController.newDocument(); Element div = document.createElement( "div" ); div.setAttribute( "xmlns", XMLController.getXHTMLNamespace() ); div.appendChild( asElement( properties, document ) ); return Content.xhtml( div ); } /** * Parses XOXO formatted XHTML into a Properties object. * * @param dl A DOM element corresponding to the &lt;dl&gt; list * @return a set of properties * @throws LuceneException */ public static Properties asProperties (Element dl) throws LuceneException { Properties properties = new Properties(); Field[] fields = asFields( dl ); for( int i = 0; i < fields.length; i++ ) { Field field = fields[ i ]; properties.setProperty( field.name(), field.stringValue() ); } return properties; } /** * Transforms a given &lt;dl&gt; list element into an array * of fields. * * @param dl The &lt;dl&gt; list element * @return An array of fields * @throws LuceneException */ public static Field[] asFields (Element dl) throws LuceneParseException { char state = 't'; // collecting <dt> initially, will switch between 't' and 'd' (<dd>) List<Field> fields = new LinkedList<Field>(); String name = null; String value = null; boolean indexed = false; boolean stored = false; boolean tokenized = false; boolean termVectorStored = false; NodeList nodes = dl.getChildNodes(); for( int i = 0; i < nodes.getLength(); i++ ) { Node node = nodes.item( i ); switch( node.getNodeType() ) { case Node.ELEMENT_NODE: Element element = (Element) node; if( element.getTagName().equals( "dt" ) ) { if( state == 't' ) { name = element.getFirstChild().getNodeValue(); indexed = false; stored = false; tokenized = false; termVectorStored = false; String classString = element.getAttribute( "class" ); if( classString != null ) { String[] classes = classString.split( " " ); for( int j = 0; j < classes.length; j++ ) { String _class = classes[ j ]; if( _class.equals( "indexed" ) ) indexed = true; if( _class.equals( "stored" ) ) stored = true; if( _class.equals( "tokenized" ) ) tokenized = true; if( _class.toLowerCase().equals( "termvectorstored" ) ) termVectorStored = true; } } state = 'd'; } else { //properties.setProperty( name, value ); fields.add( asField( name, value, indexed, stored, tokenized, termVectorStored ) ); state = 't'; } } if( element.getTagName().equals( "dd" ) ) { if( state == 'd' ) { if( element.getFirstChild() == null ) value = null; else value = element.getFirstChild().getNodeValue(); if( name != null && value != null ) { fields.add( asField( name, value, stored, indexed, tokenized, termVectorStored ) ); } value = null; state = 't'; } else { } } break; } } return fields.toArray( new Field[]{} ); } /** * Produces a new Field object given the standard field constructor * parameters. If the requested field is not stored, not indexed and * not tokenized (a dud, so to speak), a field as constructed by * {@link org.apache.lucene.document.Field#Text} will be returned. * * @param name * @param value * @param stored * @param indexed * @param tokenized * @param termVectorStored * @return a field */ protected static Field asField (String name, String value, boolean stored, boolean indexed, boolean tokenized, boolean termVectorStored) { Field.Store store = stored ? Field.Store.YES : Field.Store.NO; Field.Index index = Field.Index.NO; if( indexed ) { index = tokenized ? Field.Index.TOKENIZED : Field.Index.UN_TOKENIZED; } Field.TermVector termVector = termVectorStored ? Field.TermVector.YES : Field.TermVector.NO; if( store == Field.Store.NO && index == Field.Index.NO ) { store = Field.Store.YES; index = Field.Index.TOKENIZED; } return new Field( name, value, store, index, termVector ); } }
package dr.evomodelxml.treelikelihood; import dr.evolution.alignment.PatternList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.tree.TreeModel; import dr.evomodel.treelikelihood.TipPartialsModel; import dr.evomodel.treelikelihood.TreeLikelihood; import dr.xml.*; public class TreeLikelihoodParser extends AbstractXMLObjectParser { public static final String TREE_LIKELIHOOD = "treeLikelihood"; public static final String ANCESTRAL_TREE_LIKELIHOOD = "ancestralTreeLikelihood"; public static final String USE_AMBIGUITIES = "useAmbiguities"; public static final String ALLOW_MISSING_TAXA = "allowMissingTaxa"; public static final String STORE_PARTIALS = "storePartials"; public static final String SCALING_FACTOR = "scalingFactor"; public static final String SCALING_THRESHOLD = "scalingThreshold"; public static final String FORCE_JAVA_CORE = "forceJavaCore"; public static final String FORCE_RESCALING = "forceRescaling"; public String getParserName() { return TREE_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false); boolean allowMissingTaxa = xo.getAttribute(ALLOW_MISSING_TAXA, false); boolean storePartials = xo.getAttribute(STORE_PARTIALS, true); boolean forceJavaCore = xo.getAttribute(FORCE_JAVA_CORE, false); if (Boolean.valueOf(System.getProperty("java_only"))) { forceJavaCore = true; } PatternList patternList = (PatternList) xo.getChild(PatternList.class); TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); TipPartialsModel tipPartialsModel = (TipPartialsModel) xo.getChild(TipPartialsModel.class); boolean forceRescaling = xo.getAttribute(FORCE_RESCALING, false); return new TreeLikelihood( patternList, treeModel, siteModel, branchRateModel, tipPartialsModel, useAmbiguities, allowMissingTaxa, storePartials, forceJavaCore, forceRescaling); }
package edu.umd.cs.findbugs.gui; import java.awt.CardLayout; import java.awt.Component; import java.awt.Cursor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; import javax.swing.filechooser.*; import edu.umd.cs.daveho.ba.SourceFinder; import edu.umd.cs.findbugs.*; /** * The main GUI frame for FindBugs. * * @author David Hovemeyer */ public class FindBugsFrame extends javax.swing.JFrame { /** * Custom cell renderer for the navigator tree. */ private static class NavigatorCellRenderer extends DefaultTreeCellRenderer { private ImageIcon projectIcon; private ImageIcon analysisRunIcon; public NavigatorCellRenderer() { ClassLoader classLoader = this.getClass().getClassLoader(); projectIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/project.png")); analysisRunIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/execute.png")); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); // Set the icon, depending on what kind of node it is DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object obj = node.getUserObject(); if (obj instanceof Project) { setIcon(projectIcon); } else if (obj instanceof AnalysisRun) { setIcon(analysisRunIcon); } return this; } } /** * Custom cell renderer for the bug tree. */ private static class BugCellRenderer extends DefaultTreeCellRenderer { private ImageIcon bugGroupIcon; private ImageIcon packageIcon; private ImageIcon bugIcon; private ImageIcon classIcon; private ImageIcon methodIcon; private ImageIcon fieldIcon; private ImageIcon sourceFileIcon; public BugCellRenderer() { ClassLoader classLoader = this.getClass().getClassLoader(); bugGroupIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/bug.png")); packageIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/package.png")); bugIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/bug2.png")); classIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/class.png")); methodIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/method.png")); fieldIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/field.png")); sourceFileIcon = new ImageIcon(classLoader.getResource("edu/umd/cs/findbugs/gui/sourcefile.png")); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); // Set the icon, depending on what kind of node it is DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object obj = node.getUserObject(); if (obj instanceof BugInstance) { setIcon(bugIcon); } else if (obj instanceof ClassAnnotation) { setIcon(classIcon); } else if (obj instanceof MethodAnnotation) { setIcon(methodIcon); } else if (obj instanceof FieldAnnotation) { setIcon(fieldIcon); } else if (obj instanceof SourceLineAnnotation) { setIcon(sourceFileIcon); } else if (obj instanceof BugInstanceGroup) { // This is a "group" node BugInstanceGroup groupNode = (BugInstanceGroup) obj; String groupType = groupNode.getGroupType(); if (groupType == GROUP_BY_CLASS) { setIcon(classIcon); } else if (groupType == GROUP_BY_PACKAGE) { setIcon(packageIcon); } else if (groupType == GROUP_BY_BUG_TYPE) { setIcon(bugGroupIcon); } } else { setIcon(null); } return this; } } /** Compare BugInstance class names. */ private static class BugInstanceClassComparator implements Comparator { public int compare(Object a, Object b) { BugInstance lhs = (BugInstance) a; BugInstance rhs = (BugInstance) b; return lhs.getPrimaryClass().compareTo(rhs.getPrimaryClass()); } } private static final Comparator bugInstanceClassComparator = new BugInstanceClassComparator(); /** Compare BugInstance package names. */ private static class BugInstancePackageComparator implements Comparator { public int compare(Object a, Object b) { BugInstance lhs = (BugInstance) a; BugInstance rhs = (BugInstance) b; return lhs.getPrimaryClass().getPackageName().compareTo( rhs.getPrimaryClass().getPackageName()); } } private static final Comparator bugInstancePackageComparator = new BugInstancePackageComparator(); /** Compare BugInstance bug types. */ private static class BugInstanceTypeComparator implements Comparator { public int compare(Object a, Object b) { BugInstance lhs = (BugInstance) a; BugInstance rhs = (BugInstance) b; String lhsString = lhs.toString(); String rhsString = rhs.toString(); return lhsString.substring(0, lhsString.indexOf(':')).compareTo( rhsString.substring(0, rhsString.indexOf(':'))); } } private static final Comparator bugInstanceTypeComparator = new BugInstanceTypeComparator(); /** Compare BugInstances by class name. */ private static class BugInstanceByClassComparator implements Comparator { public int compare(Object a, Object b) { int cmp = bugInstanceClassComparator.compare(a, b); if (cmp != 0) return cmp; return ((Comparable)a).compareTo(b); } } private static final Comparator bugInstanceByClassComparator = new FindBugsFrame.BugInstanceByClassComparator(); /** Compare BugInstances by package name. */ private static class BugInstanceByPackageComparator implements Comparator { public int compare(Object a, Object b) { int cmp = bugInstancePackageComparator.compare(a, b); if (cmp != 0) return cmp; return ((Comparable)a).compareTo(b); } } private static final Comparator bugInstanceByPackageComparator = new FindBugsFrame.BugInstanceByPackageComparator(); private static class BugInstanceByCategoryComparator implements Comparator { public int compare(Object a, Object b) { int cmp = bugInstanceTypeComparator.compare(a, b); if (cmp != 0) return cmp; return ((Comparable)a).compareTo(b); } } private static final Comparator bugInstanceByCategoryComparator = new FindBugsFrame.BugInstanceByCategoryComparator(); private static final String GROUP_BY_CLASS = "By class"; private static final String GROUP_BY_PACKAGE = "By package"; private static final String GROUP_BY_BUG_TYPE = "By bug type"; /** Creates new form FindBugsFrame */ public FindBugsFrame() { initComponents(); postInitComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ private void initComponents() {//GEN-BEGIN:initComponents java.awt.GridBagConstraints gridBagConstraints; consoleSplitter = new javax.swing.JSplitPane(); navigatorViewSplitter = new javax.swing.JSplitPane(); jScrollPane1 = new javax.swing.JScrollPane(); navigatorTree = new javax.swing.JTree(); viewPanel = new javax.swing.JPanel(); emptyPanel = new javax.swing.JPanel(); reportPanel = new javax.swing.JPanel(); editProjectPanel = new javax.swing.JPanel(); jarFileLabel = new javax.swing.JLabel(); jarNameTextField = new javax.swing.JTextField(); addJarButton = new javax.swing.JButton(); jarFileListLabel = new javax.swing.JLabel(); sourceDirLabel = new javax.swing.JLabel(); srcDirTextField = new javax.swing.JTextField(); addSourceDirButton = new javax.swing.JButton(); sourceDirListLabel = new javax.swing.JLabel(); removeJarButton = new javax.swing.JButton(); removeSrcDirButton = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); browseJarButton = new javax.swing.JButton(); browseSrcDirButton = new javax.swing.JButton(); editProjectLabel = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); findBugsButton = new javax.swing.JButton(); jSeparator4 = new javax.swing.JSeparator(); jScrollPane2 = new javax.swing.JScrollPane(); jarFileList = new javax.swing.JList(); jScrollPane3 = new javax.swing.JScrollPane(); sourceDirList = new javax.swing.JList(); bugTreePanel = new javax.swing.JPanel(); groupByChooser = new javax.swing.JComboBox(); groupByLabel = new javax.swing.JLabel(); bugTreeSourceViewSplitter = new javax.swing.JSplitPane(); jScrollPane4 = new javax.swing.JScrollPane(); bugTree = new javax.swing.JTree(); jScrollPane6 = new javax.swing.JScrollPane(); sourceTextArea = new javax.swing.JTextArea(); jScrollPane5 = new javax.swing.JScrollPane(); consoleMessageArea = new javax.swing.JTextArea(); jMenuBar1 = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); newProjectItem = new javax.swing.JMenuItem(); openProjectItem = new javax.swing.JMenuItem(); closeProjectItem = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JSeparator(); exitItem = new javax.swing.JMenuItem(); viewMenu = new javax.swing.JMenu(); viewConsoleItem = new javax.swing.JCheckBoxMenuItem(); helpMenu = new javax.swing.JMenu(); aboutItem = new javax.swing.JMenuItem(); setTitle("FindBugs"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); consoleSplitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); consoleSplitter.setResizeWeight(1.0); consoleSplitter.setOneTouchExpandable(true); consoleSplitter.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { consoleSplitterPropertyChange(evt); } }); jScrollPane1.setPreferredSize(new java.awt.Dimension(140, 0)); navigatorTree.setModel(createNavigatorTreeModel()); jScrollPane1.setViewportView(navigatorTree); navigatorViewSplitter.setLeftComponent(jScrollPane1); viewPanel.setLayout(new java.awt.CardLayout()); viewPanel.add(emptyPanel, "EmptyPanel"); viewPanel.add(reportPanel, "ReportPanel"); editProjectPanel.setLayout(new java.awt.GridBagLayout()); jarFileLabel.setFont(new java.awt.Font("Dialog", 0, 12)); jarFileLabel.setText("Jar file:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(jarFileLabel, gridBagConstraints); jarNameTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jarNameTextFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); editProjectPanel.add(jarNameTextField, gridBagConstraints); addJarButton.setFont(new java.awt.Font("Dialog", 0, 12)); addJarButton.setText("Add"); addJarButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addJarButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(addJarButton, gridBagConstraints); jarFileListLabel.setFont(new java.awt.Font("Dialog", 0, 12)); jarFileListLabel.setText("Jar Files:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(jarFileListLabel, gridBagConstraints); sourceDirLabel.setFont(new java.awt.Font("Dialog", 0, 12)); sourceDirLabel.setText("Source Dir:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(sourceDirLabel, gridBagConstraints); srcDirTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { srcDirTextFieldActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); editProjectPanel.add(srcDirTextField, gridBagConstraints); addSourceDirButton.setFont(new java.awt.Font("Dialog", 0, 12)); addSourceDirButton.setText("Add"); addSourceDirButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addSourceDirButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(addSourceDirButton, gridBagConstraints); sourceDirListLabel.setFont(new java.awt.Font("Dialog", 0, 12)); sourceDirListLabel.setText("Source Dirs:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(sourceDirListLabel, gridBagConstraints); removeJarButton.setFont(new java.awt.Font("Dialog", 0, 12)); removeJarButton.setText("Remove"); removeJarButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeJarButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(removeJarButton, gridBagConstraints); removeSrcDirButton.setFont(new java.awt.Font("Dialog", 0, 12)); removeSrcDirButton.setText("Remove"); removeSrcDirButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeSrcDirButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(removeSrcDirButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3); editProjectPanel.add(jSeparator1, gridBagConstraints); browseJarButton.setText("..."); browseJarButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseJarButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 3; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(browseJarButton, gridBagConstraints); browseSrcDirButton.setText("..."); browseSrcDirButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseSrcDirButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 6; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(browseSrcDirButton, gridBagConstraints); editProjectLabel.setBackground(new java.awt.Color(0, 0, 204)); editProjectLabel.setFont(new java.awt.Font("Dialog", 1, 24)); editProjectLabel.setForeground(new java.awt.Color(255, 255, 255)); editProjectLabel.setText("Project"); editProjectLabel.setOpaque(true); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; editProjectPanel.add(editProjectLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3); editProjectPanel.add(jSeparator2, gridBagConstraints); findBugsButton.setText("Find Bugs!"); findBugsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { findBugsButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 9; gridBagConstraints.gridwidth = 4; gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3); editProjectPanel.add(findBugsButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3); editProjectPanel.add(jSeparator4, gridBagConstraints); jScrollPane2.setPreferredSize(new java.awt.Dimension(259, 1)); jarFileList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED)); jarFileList.setFont(new java.awt.Font("Dialog", 0, 12)); jarFileList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(jarFileList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weighty = 0.7; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(jScrollPane2, gridBagConstraints); jScrollPane3.setPreferredSize(new java.awt.Dimension(259, 1)); sourceDirList.setBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED)); sourceDirList.setFont(new java.awt.Font("Dialog", 0, 12)); sourceDirList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane3.setViewportView(sourceDirList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weighty = 0.3; gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 3); editProjectPanel.add(jScrollPane3, gridBagConstraints); viewPanel.add(editProjectPanel, "EditProjectPanel"); bugTreePanel.setLayout(new java.awt.GridBagLayout()); groupByChooser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { groupByChooserActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; bugTreePanel.add(groupByChooser, gridBagConstraints); groupByLabel.setFont(new java.awt.Font("Dialog", 0, 12)); groupByLabel.setText("Group:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; bugTreePanel.add(groupByLabel, gridBagConstraints); bugTreeSourceViewSplitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); bugTreeSourceViewSplitter.setResizeWeight(1.0); bugTreeSourceViewSplitter.setToolTipText("null"); bugTreeSourceViewSplitter.setOneTouchExpandable(true); bugTree.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { bugTreeMousePressed(evt); } }); jScrollPane4.setViewportView(bugTree); bugTreeSourceViewSplitter.setLeftComponent(jScrollPane4); jScrollPane6.setPreferredSize(new java.awt.Dimension(0, 100)); sourceTextArea.setPreferredSize(new java.awt.Dimension(0, 5)); jScrollPane6.setViewportView(sourceTextArea); bugTreeSourceViewSplitter.setRightComponent(jScrollPane6); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; bugTreePanel.add(bugTreeSourceViewSplitter, gridBagConstraints); viewPanel.add(bugTreePanel, "BugTree"); navigatorViewSplitter.setRightComponent(viewPanel); consoleSplitter.setTopComponent(navigatorViewSplitter); jScrollPane5.setMinimumSize(new java.awt.Dimension(22, 100)); jScrollPane5.setPreferredSize(new java.awt.Dimension(0, 100)); consoleMessageArea.setBackground(new java.awt.Color(204, 204, 204)); consoleMessageArea.setEditable(false); consoleMessageArea.setFont(new java.awt.Font("Courier", 0, 12)); consoleMessageArea.setMinimumSize(new java.awt.Dimension(0, 0)); consoleMessageArea.setPreferredSize(new java.awt.Dimension(0, 5)); jScrollPane5.setViewportView(consoleMessageArea); consoleSplitter.setBottomComponent(jScrollPane5); getContentPane().add(consoleSplitter, java.awt.BorderLayout.CENTER); jMenuBar1.setFont(new java.awt.Font("Dialog", 0, 12)); fileMenu.setMnemonic('F'); fileMenu.setText("File"); fileMenu.setFont(new java.awt.Font("Dialog", 0, 12)); newProjectItem.setFont(new java.awt.Font("Dialog", 0, 12)); newProjectItem.setMnemonic('N'); newProjectItem.setText("New Project"); newProjectItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProjectItemActionPerformed(evt); } }); fileMenu.add(newProjectItem); openProjectItem.setFont(new java.awt.Font("Dialog", 0, 12)); openProjectItem.setMnemonic('O'); openProjectItem.setText("Open Project"); fileMenu.add(openProjectItem); closeProjectItem.setFont(new java.awt.Font("Dialog", 0, 12)); closeProjectItem.setMnemonic('C'); closeProjectItem.setText("Close Project"); fileMenu.add(closeProjectItem); fileMenu.add(jSeparator3); exitItem.setFont(new java.awt.Font("Dialog", 0, 12)); exitItem.setMnemonic('X'); exitItem.setText("Exit"); exitItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitItemActionPerformed(evt); } }); fileMenu.add(exitItem); jMenuBar1.add(fileMenu); viewMenu.setMnemonic('V'); viewMenu.setText("View"); viewMenu.setFont(new java.awt.Font("Dialog", 0, 12)); viewConsoleItem.setMnemonic('C'); viewConsoleItem.setSelected(true); viewConsoleItem.setText("Console"); viewConsoleItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewConsoleItemActionPerformed(evt); } }); viewMenu.add(viewConsoleItem); jMenuBar1.add(viewMenu); helpMenu.setMnemonic('H'); helpMenu.setText("Help"); helpMenu.setFont(new java.awt.Font("Dialog", 0, 12)); aboutItem.setFont(new java.awt.Font("Dialog", 0, 12)); aboutItem.setMnemonic('A'); aboutItem.setText("About"); aboutItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutItemActionPerformed(evt); } }); helpMenu.add(aboutItem); jMenuBar1.add(helpMenu); setJMenuBar(jMenuBar1); pack(); }//GEN-END:initComponents private void bugTreeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bugTreeMousePressed if (evt.getClickCount() == 2) { TreePath selection = bugTree.getSelectionPath(); DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) selection.getLastPathComponent(); Object obj = selNode.getUserObject(); if (obj instanceof SourceLineAnnotation) { SourceLineAnnotation srcLine = (SourceLineAnnotation) obj; Project project = getCurrentProject(); AnalysisRun analysisRun = getCurrentAnalysisRun(); viewSource(project, analysisRun, srcLine); } } }//GEN-LAST:event_bugTreeMousePressed private void aboutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutItemActionPerformed AboutDialog dialog = new AboutDialog(this, true); dialog.setLocationRelativeTo(null); // center the dialog dialog.show(); }//GEN-LAST:event_aboutItemActionPerformed /** * A fudge value required in our hack to get the REAL maximum * divider location for the consoleSplitter. Experience suggests that * the value "1" would work here, but setting it a little higher * makes the code a bit more robust. */ private static final int DIVIDER_FUDGE = 3; private void consoleSplitterPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_consoleSplitterPropertyChange // The idea here is to keep the View:Console checkbox up to date with // the real location of the divider of the consoleSplitter. // What we want is if any part of the console window is visible, // then the checkbox should be checked. String propertyName = evt.getPropertyName(); if (propertyName.equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { Integer location = (Integer) evt.getNewValue(); // FIXME - I need to find out the REAL maximum divider value. // getMaximumDividerLocation() is based on minimum component sizes, // but it may be violated if the user clicks the little "contracter" // button put in place when the "one touch expandable" property was set. // Here is a nasty hack which makes a guess based on the current size // of the frame's content pane. int contentPaneHeight = this.getContentPane().getHeight(); int hopefullyMaxDivider = contentPaneHeight - (consoleSplitter.getDividerSize() + DIVIDER_FUDGE); /* System.out.println("pane height = " + contentPaneHeight + ", dividerLoc=" + location.intValue() + ", hopefullyMaxDivider=" + hopefullyMaxDivider); */ viewConsoleItem.setSelected(location.intValue() < hopefullyMaxDivider); } }//GEN-LAST:event_consoleSplitterPropertyChange private void viewConsoleItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewConsoleItemActionPerformed if (viewConsoleItem.isSelected()) { consoleSplitter.resetToPreferredSizes(); } else { consoleSplitter.setDividerLocation(1.0); } }//GEN-LAST:event_viewConsoleItemActionPerformed private void groupByChooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_groupByChooserActionPerformed String selection = groupByChooser.getSelectedItem().toString(); if (selection != null && currentAnalysisRun != null) populateAnalysisRunTreeModel(currentAnalysisRun, selection); }//GEN-LAST:event_groupByChooserActionPerformed private void findBugsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findBugsButtonActionPerformed Project project = getCurrentProject(); AnalysisRun analysisRun = new AnalysisRun(project, logger); logger.logMessage(ConsoleLogger.INFO, "Beginning analysis of " + project); // Run the analysis! RunAnalysisDialog dialog = new RunAnalysisDialog(this, analysisRun); dialog.setSize(400, 300); dialog.setLocationRelativeTo(null); // center the dialog dialog.show(); if (dialog.isCompleted()) { logger.logMessage(ConsoleLogger.INFO, "Analysis " + project + " completed"); // Create a navigator tree node for the analysis run DefaultTreeModel treeModel = (DefaultTreeModel) navigatorTree.getModel(); TreePath treePath = navigatorTree.getSelectionPath(); DefaultMutableTreeNode projectNode = (DefaultMutableTreeNode) treePath.getPath()[1]; DefaultMutableTreeNode analysisRunNode = new DefaultMutableTreeNode(analysisRun); treeModel.insertNodeInto(analysisRunNode, projectNode, projectNode.getChildCount()); // Make the new node the currently selected node TreePath path = new TreePath(new Object[]{rootNode, projectNode, analysisRunNode}); navigatorTree.makeVisible(path); navigatorTree.setSelectionPath(path); } else { logger.logMessage(ConsoleLogger.INFO, "Analysis of " + project + " cancelled by user"); } }//GEN-LAST:event_findBugsButtonActionPerformed private void browseSrcDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseSrcDirButtonActionPerformed JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int rc = chooser.showDialog(this, "Add source directory"); if (rc == JFileChooser.APPROVE_OPTION) { srcDirTextField.setText(chooser.getSelectedFile().getPath()); addSourceDirToList(); } }//GEN-LAST:event_browseSrcDirButtonActionPerformed private void srcDirTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_srcDirTextFieldActionPerformed addSourceDirToList(); }//GEN-LAST:event_srcDirTextFieldActionPerformed private void jarNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jarNameTextFieldActionPerformed addJarToList(); }//GEN-LAST:event_jarNameTextFieldActionPerformed private void browseJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseJarButtonActionPerformed JFileChooser chooser = new JFileChooser(); FileFilter filter = new FileFilter() { public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".jar"); } public String getDescription() { return "Jar files (*.jar)"; } }; chooser.setFileFilter(filter); int rc = chooser.showDialog(this, "Add Jar file"); if (rc == JFileChooser.APPROVE_OPTION) { jarNameTextField.setText(chooser.getSelectedFile().getPath()); addJarToList(); } }//GEN-LAST:event_browseJarButtonActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened navigatorTree.setSelectionPath(new TreePath(rootNode)); }//GEN-LAST:event_formWindowOpened private void newProjectItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProjectItemActionPerformed String projectName = "<<project " + (++projectCount) + ">>"; System.out.println("Adding " + projectName); Project project = new Project(projectName); projectCollection.addProject(project); DefaultMutableTreeNode projectNode = new DefaultMutableTreeNode(project); DefaultTreeModel treeModel = (DefaultTreeModel) navigatorTree.getModel(); treeModel.insertNodeInto(projectNode, rootNode, rootNode.getChildCount()); TreePath projPath = new TreePath(new Object[]{rootNode, projectNode}); navigatorTree.makeVisible(projPath); navigatorTree.setSelectionPath(projPath); }//GEN-LAST:event_newProjectItemActionPerformed private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed exitFindBugs(); }//GEN-LAST:event_exitItemActionPerformed private void removeSrcDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeSrcDirButtonActionPerformed int selIndex = sourceDirList.getSelectedIndex(); if (selIndex >= 0) { Project project = getCurrentProject(); project.removeSourceDir(selIndex); DefaultListModel listModel = (DefaultListModel) sourceDirList.getModel(); listModel.removeElementAt(selIndex); } }//GEN-LAST:event_removeSrcDirButtonActionPerformed private void removeJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeJarButtonActionPerformed int selIndex = jarFileList.getSelectedIndex(); if (selIndex >= 0) { Project project = getCurrentProject(); project.removeJarFile(selIndex); DefaultListModel listModel = (DefaultListModel) jarFileList.getModel(); listModel.removeElementAt(selIndex); } }//GEN-LAST:event_removeJarButtonActionPerformed private void addSourceDirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSourceDirButtonActionPerformed addSourceDirToList(); }//GEN-LAST:event_addSourceDirButtonActionPerformed private void addJarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addJarButtonActionPerformed addJarToList(); }//GEN-LAST:event_addJarButtonActionPerformed /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm exitFindBugs(); }//GEN-LAST:event_exitForm /** * Create the tree model that will be used by the navigator tree. */ private TreeModel createNavigatorTreeModel() { projectCollection = new ProjectCollection(); rootNode = new DefaultMutableTreeNode(projectCollection); navigatorTreeModel = new DefaultTreeModel(rootNode); return navigatorTreeModel; } /** * This is called from the constructor to perform post-initialization * of the components in the form. */ private void postInitComponents() { logger = new ConsoleLogger(this); viewPanelLayout = (CardLayout) viewPanel.getLayout(); navigatorTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // Add a tree selection listener to the navigator tree, so we can // ensure that the view is always consistent with the current selection. navigatorTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { navigatorTreeSelectionChanged(e); } }); navigatorTree.setCellRenderer(new FindBugsFrame.NavigatorCellRenderer()); navigatorTree.setRootVisible(false); navigatorTree.setShowsRootHandles(false); bugTree.setCellRenderer(new FindBugsFrame.BugCellRenderer()); bugTree.setRootVisible(false); bugTree.setShowsRootHandles(true); jarFileList.setModel(new DefaultListModel()); sourceDirList.setModel(new DefaultListModel()); groupByChooser.addItem(GROUP_BY_CLASS); groupByChooser.addItem(GROUP_BY_PACKAGE); groupByChooser.addItem(GROUP_BY_BUG_TYPE); bugTreeSourceViewSplitter.setDividerLocation(1.0); } /** * This handler is called whenever the selection in the navigator * tree changes. * @param e the TreeSelectionEvent */ private void navigatorTreeSelectionChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) navigatorTree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof ProjectCollection) { // Project collection node - there is no view associated with this node setView("EmptyPanel"); } else if (nodeInfo instanceof Project) { synchProject((Project) nodeInfo); setView("EditProjectPanel"); } else if (nodeInfo instanceof AnalysisRun) { synchAnalysisRun((AnalysisRun) nodeInfo); setView("BugTree"); } } /** * Get the currently selected project. * @return the current project, or null if no project is selected * (which should only be possible if the root node is selected) */ private Project getCurrentProject() { return (Project) getNavigatorSelectionOf(Project.class); } /** * Get the currently selected analysis run. */ private AnalysisRun getCurrentAnalysisRun() { return (AnalysisRun) getNavigatorSelectionOf(AnalysisRun.class); } private Object getNavigatorSelectionOf(Class c) { TreePath selPath = navigatorTree.getSelectionPath(); // Work backwards from end until we get to the kind of // object we're looking for. Object[] nodeList = selPath.getPath(); for (int i = nodeList.length - 1; i >= 0; --i) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeList[i]; Object nodeInfo = node.getUserObject(); if (nodeInfo.getClass() == c) return nodeInfo; } return null; } /** * Synchronize the edit project dialog with given project. * @param project the selected project */ private void synchProject(Project project) { System.out.println("Synch with project " + project.toString()); // Clear text fields jarNameTextField.setText(""); srcDirTextField.setText(""); // Populate jar and source dir lists DefaultListModel jarListModel = (DefaultListModel) jarFileList.getModel(); jarListModel.clear(); for (int i = 0; i < project.getNumJarFiles(); ++i) { jarListModel.addElement(project.getJarFile(i)); } DefaultListModel srcDirListModel = (DefaultListModel) sourceDirList.getModel(); srcDirListModel.clear(); for (int i = 0; i < project.getNumSourceDirs(); ++i) { srcDirListModel.addElement(project.getSourceDir(i)); } } /** * Synchronize the bug tree with the given analysisRun object. * @param analysisRun the selected analysis run */ private void synchAnalysisRun(AnalysisRun analysisRun) { boolean modelChanged = false; if (analysisRun != currentAnalysisRun) { modelChanged = true; // If this is the first time the analysis run is being shown in // the bug tree, it won't have a tree model yet. if (analysisRun.getTreeModel() == null) { DefaultMutableTreeNode bugRootNode = new DefaultMutableTreeNode(); DefaultTreeModel bugTreeModel = new DefaultTreeModel(bugRootNode); analysisRun.setTreeModel(bugTreeModel); } } // Make sure that the sort order is correct. String currentSortOrder = groupByChooser.getSelectedItem().toString(); if (!analysisRun.getSortOrder().equals(currentSortOrder)) { populateAnalysisRunTreeModel(analysisRun, currentSortOrder); } if (modelChanged) { bugTree.setModel(analysisRun.getTreeModel()); currentAnalysisRun = analysisRun; } // TODO: restore state of tree! I.e., which nodes expanded, and selection } /** * Populate an analysis run's tree model for given sort order. */ private void populateAnalysisRunTreeModel(AnalysisRun analysisRun, final String groupBy) { // Set busy cursor - this is potentially a time-consuming operation Cursor orig = this.getCursor(); this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final DefaultTreeModel bugTreeModel = analysisRun.getTreeModel(); final DefaultMutableTreeNode bugRootNode = (DefaultMutableTreeNode) bugTreeModel.getRoot(); // Delete all children from root node bugRootNode.removeAllChildren(); // Sort the instances TreeSet sortedCollection = new TreeSet(getBugInstanceComparator(groupBy)); sortedCollection.addAll(analysisRun.getBugInstances()); // The grouper callback is what actually adds the group and bug // nodes to the tree. Grouper.Callback callback = new Grouper.Callback() { private BugInstanceGroup currentGroup; private DefaultMutableTreeNode currentGroupNode; public void startGroup(Object member_) { BugInstance member = (BugInstance) member_; String groupName; if (groupBy == GROUP_BY_CLASS) groupName = member.getPrimaryClass().getClassName(); else if (groupBy == GROUP_BY_PACKAGE) groupName = member.getPrimaryClass().getPackageName(); else if (groupBy == GROUP_BY_BUG_TYPE) { String desc = member.toString(); groupName = desc.substring(0, desc.indexOf(':')); } else throw new IllegalStateException("Unknown sort order: " + groupBy); currentGroup = new BugInstanceGroup(groupBy, groupName); currentGroupNode = new DefaultMutableTreeNode(currentGroup); bugTreeModel.insertNodeInto(currentGroupNode, bugRootNode, bugRootNode.getChildCount()); insertIntoGroup(member); } public void addToGroup(Object member_) { BugInstance member = (BugInstance) member_; insertIntoGroup(member); } private void insertIntoGroup(BugInstance member) { currentGroup.incrementMemberCount(); DefaultMutableTreeNode bugNode = new DefaultMutableTreeNode(member); bugTreeModel.insertNodeInto(bugNode, currentGroupNode, currentGroupNode.getChildCount()); // Insert annotations Iterator j = member.annotationIterator(); while (j.hasNext()) { BugAnnotation annotation = (BugAnnotation) j.next(); DefaultMutableTreeNode annotationNode = new DefaultMutableTreeNode(annotation); bugTreeModel.insertNodeInto(annotationNode, bugNode, bugNode.getChildCount()); } } }; // Create the grouper, and execute it to populate the bug tree Grouper grouper = new Grouper(callback); Comparator groupComparator = getGroupComparator(groupBy); grouper.group(sortedCollection, groupComparator); // Sort order is up to date now analysisRun.setSortOrder(groupBy); // Let the tree know it needs to update itself bugTreeModel.nodeStructureChanged(bugRootNode); // Now we're done this.setCursor(orig); } /** * Get a BugInstance Comparator for given sort order. */ private Comparator getBugInstanceComparator(String sortOrder) { if (sortOrder.equals(GROUP_BY_CLASS)) return bugInstanceByClassComparator; else if (sortOrder.equals(GROUP_BY_PACKAGE)) return bugInstanceByPackageComparator; else if (sortOrder.equals(GROUP_BY_BUG_TYPE)) return bugInstanceByCategoryComparator; else throw new IllegalArgumentException("Bad sort order: " + sortOrder); } /** * Get a Grouper for a given sort order. */ private Comparator getGroupComparator(String groupBy) { if (groupBy.equals(GROUP_BY_CLASS)) { return bugInstanceClassComparator; } else if (groupBy.equals(GROUP_BY_PACKAGE)) { return bugInstancePackageComparator; } else if (groupBy.equals(GROUP_BY_BUG_TYPE)) { return bugInstanceTypeComparator; } else throw new IllegalArgumentException("Bad sort order: " + groupBy); } private void exitFindBugs() { // TODO: offer to save work, etc. System.exit(0); } /** * Set the view panel to display the named view. */ private void setView(String viewName) { viewPanelLayout.show(viewPanel, viewName); } /** * Called to add the jar file in the jarNameTextField to the * Jar file list (and the project it represents). */ private void addJarToList() { String jarFile = jarNameTextField.getText(); if (!jarFile.equals("")) { Project project = getCurrentProject(); project.addJar(jarFile); DefaultListModel listModel = (DefaultListModel) jarFileList.getModel(); listModel.addElement(jarFile); jarNameTextField.setText(""); } } /** * Called to add the source directory in the sourceDirTextField * to the source directory list (and the project it represents). */ private void addSourceDirToList() { String sourceDir = srcDirTextField.getText(); if (!sourceDir.equals("")) { Project project = getCurrentProject(); project.addSourceDir(sourceDir); DefaultListModel listModel = (DefaultListModel) sourceDirList.getModel(); listModel.addElement(sourceDir); srcDirTextField.setText(""); } } private void viewSource(Project project, AnalysisRun analysisRun, SourceLineAnnotation srcLine) { sourceFinder.setSourceBaseList(project.getSourceDirList()); String sourceFile = analysisRun.getSourceFile(srcLine.getClassName()); if (sourceFile == null) { System.out.println("No source file for class " + srcLine.getClassName()); return; } sourceTextArea.setText(""); bugTreeSourceViewSplitter.resetToPreferredSizes(); // Try to open the source file and display its contents // in the source text area. try { InputStream in = sourceFinder.openSource(srcLine.getPackageName(), sourceFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { sourceTextArea.append(line + "\n"); } reader.close(); } catch (IOException e) { logger.logMessage(ConsoleLogger.ERROR, e.getMessage()); return; } // TODO: highlight the selected source line(s) } /** * Write a message to the console window. */ public void writeToConsole(String message) { consoleMessageArea.append(message); consoleMessageArea.append("\n"); } /** * @param args the command line arguments */ public static void main(String args[]) { FindBugsFrame frame = new FindBugsFrame(); frame.setSize(800, 600); frame.show(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel editProjectLabel; private javax.swing.JButton removeSrcDirButton; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator4; private javax.swing.JMenu viewMenu; private javax.swing.JMenu fileMenu; private javax.swing.JMenuItem newProjectItem; private javax.swing.JMenuItem openProjectItem; private javax.swing.JSplitPane consoleSplitter; private javax.swing.JList jarFileList; private javax.swing.JLabel jarFileLabel; private javax.swing.JMenuItem aboutItem; private javax.swing.JButton addSourceDirButton; private javax.swing.JComboBox groupByChooser; private javax.swing.JButton removeJarButton; private javax.swing.JButton addJarButton; private javax.swing.JTree navigatorTree; private javax.swing.JList sourceDirList; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JPanel emptyPanel; private javax.swing.JSeparator jSeparator3; private javax.swing.JTextArea consoleMessageArea; private javax.swing.JTree bugTree; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JSplitPane navigatorViewSplitter; private javax.swing.JLabel groupByLabel; private javax.swing.JCheckBoxMenuItem viewConsoleItem; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JMenuItem closeProjectItem; private javax.swing.JTextField jarNameTextField; private javax.swing.JButton browseJarButton; private javax.swing.JTextArea sourceTextArea; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JButton findBugsButton; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JPanel bugTreePanel; private javax.swing.JSplitPane bugTreeSourceViewSplitter; private javax.swing.JLabel sourceDirLabel; private javax.swing.JPanel viewPanel; private javax.swing.JLabel jarFileListLabel; private javax.swing.JSeparator jSeparator1; private javax.swing.JPanel reportPanel; private javax.swing.JPanel editProjectPanel; private javax.swing.JMenu helpMenu; private javax.swing.JTextField srcDirTextField; private javax.swing.JButton browseSrcDirButton; private javax.swing.JLabel sourceDirListLabel; private javax.swing.JMenuItem exitItem; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JMenuBar jMenuBar1; // End of variables declaration//GEN-END:variables // My variable declarations private ConsoleLogger logger; private CardLayout viewPanelLayout; private ProjectCollection projectCollection; private DefaultTreeModel navigatorTreeModel; private DefaultMutableTreeNode rootNode; private int projectCount; private AnalysisRun currentAnalysisRun; // be lazy in switching tree models in BugTree private SourceFinder sourceFinder = new SourceFinder(); }
package gov.nih.nci.cananolab.ui.core; import gov.nih.nci.cananolab.domain.particle.NanoparticleSample; import gov.nih.nci.cananolab.dto.common.LabFileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.dto.particle.ParticleDataLinkBean; import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException; import gov.nih.nci.cananolab.exception.FileException; import gov.nih.nci.cananolab.service.common.FileService; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.ui.particle.InitNanoparticleSetup; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.ClassUtils; import gov.nih.nci.cananolab.util.PropertyReader; import java.io.File; import java.io.FileInputStream; import java.util.Map; import java.util.SortedSet; 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; /** * Base action for all annotation actions * * @author pansu * */ public abstract class BaseAnnotationAction extends AbstractDispatchAction { public ParticleBean setupParticle(DynaValidatorForm theForm, HttpServletRequest request) throws Exception { String particleId = request.getParameter("particleId"); if (particleId == null) { particleId = theForm.getString("particleId"); } HttpSession session = request.getSession(); UserBean user = (UserBean) session.getAttribute("user"); NanoparticleSampleService service = new NanoparticleSampleService(); ParticleBean particleBean = service .findNanoparticleSampleById(particleId); request.setAttribute("theParticle", particleBean); InitNanoparticleSetup.getInstance().getOtherParticleNames( request, particleBean.getDomainParticleSample().getName(), particleBean.getDomainParticleSample().getSource() .getOrganizationName(), user); return particleBean; } public boolean loginRequired() { return false; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } public Map<String, SortedSet<ParticleDataLinkBean>> setupDataTree( DynaValidatorForm theForm, HttpServletRequest request) throws Exception { request.setAttribute("updateDataTree", "true"); String particleId = request.getParameter("particleId"); if (particleId == null) { if (theForm.getMap().containsKey("particleSampleBean")) { particleId = ((ParticleBean) theForm.get("particleSampleBean")) .getDomainParticleSample().getId().toString(); } else { particleId = theForm.getString("particleId"); } } InitSetup.getInstance() .getDefaultAndOtherLookupTypes(request, "reportCategories", "Report", "category", "otherCategory", true); return InitNanoparticleSetup.getInstance().getDataTree(particleId, request); } public ActionForward setupDeleteAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String submitType = request.getParameter("submitType"); DynaValidatorForm theForm = (DynaValidatorForm) form; Map<String, SortedSet<ParticleDataLinkBean>> dataTree = setupDataTree( theForm, request); SortedSet<ParticleDataLinkBean> dataToDelete = dataTree.get(submitType); request.getSession().setAttribute("actionName", dataToDelete.first().getDataLink()); request.getSession().setAttribute("dataToDelete", dataToDelete); return mapping.findForward("annotationDeleteView"); } // check for cases where delete can't happen protected boolean checkDelete(HttpServletRequest request, ActionMessages msgs, String id) throws Exception { return true; } public ActionForward deleteAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String submitType = request.getParameter("submitType"); String className = InitSetup.getInstance().getObjectName(submitType, request.getSession().getServletContext()); String fullClassName = ClassUtils.getFullClass(className) .getCanonicalName(); String[] dataIds = (String[]) theForm.get("idsToDelete"); NanoparticleSampleService sampleService = new NanoparticleSampleService(); ActionMessages msgs = new ActionMessages(); for (String id : dataIds) { if (!checkDelete(request, msgs, id)) { return mapping.findForward("annotationDeleteView"); } sampleService.deleteAnnotationById(fullClassName, new Long(id)); } setupDataTree(theForm, request); ActionMessage msg = new ActionMessage("message.deleteAnnotations", submitType); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); return mapping.findForward("success"); } /** * Download action to handle file downloading and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.findFile(fileId, user); if (fileBean.getDomainFile().getUriExternal()) { response.sendRedirect(fileBean.getDomainFile().getUri()); return null; } String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getDomainFile().getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getDomainFile().getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("error.noFile"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); throw new FileException("File "+ fileBean.getDomainFile().getUri()+" doesn't exist on the server"); } return null; } protected NanoparticleSample[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { String[] otherParticles = (String[]) theForm.get("otherParticles"); if (otherParticles.length == 0) { return null; } NanoparticleSample[] particleSamples = new NanoparticleSample[otherParticles.length]; NanoparticleSampleService sampleService = new NanoparticleSampleService(); int i = 0; for (String other : otherParticles) { NanoparticleSample particleSample = sampleService .findNanoparticleSampleByName(other); particleSamples[i] = particleSample; i++; } // retrieve file contents // FileService fileService = new FileService(); // for (DerivedBioAssayDataBean file : entityBean.getFiles()) { // byte[] content = fileService.getFileContent(new Long(file.getId())); // file.setFileContent(content); // NanoparticleSampleService service = new NanoparticleSampleService(); // UserBean user = (UserBean) request.getSession().getAttribute("user"); // int i = 0; // for (String particleName : otherParticles) { // NanoparticleEntityBean newEntityBean = entityBean.copy(); // // overwrite particle // ParticleBean otherParticle = service.findNanoparticleSampleByName( // particleName, user); // newrBean.setParticle(otherParticle); // // reset view title // String timeStamp = StringUtils.convertDateToString(new Date(), // "MMddyyHHmmssSSS"); // String autoTitle = // CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX // + timeStamp; // newCharBean.setViewTitle(autoTitle); // List<DerivedBioAssayDataBean> dataList = newCharBean // .getDerivedBioAssayDataList(); // // replace particleName in path and uri with new particleName // for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { // String origUri = derivedBioAssayData.getUri(); // if (origUri != null) // derivedBioAssayData.setUri(origUri.replace(particle // .getSampleName(), particleName)); // charBeans[i] = newCharBean; return particleSamples; } }
package ijordan.matrixonator.view; import org.controlsfx.dialog.Wizard; import org.controlsfx.dialog.Wizard.WizardPane; import org.controlsfx.dialog.Wizard.LinearFlow; import ijordan.matrixonator.MainApp; import ijordan.matrixonator.model.Matrix; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; public class MatrixOverviewController { @FXML private TableView<Matrix> matrixTable; @FXML private TableColumn<Matrix, String> nameColumn; @FXML private TableColumn<Matrix, Integer> numRowsColumn; @FXML private TableColumn<Matrix, Integer> numColsColumn; @FXML private Label nameLabel; @FXML private Label numRowsLabel; @FXML private Label numColsLabel; @FXML private Label createdDateLabel; // Reference to the main application. private MainApp mainApp; /** * The constructor. The constructor is called before the initialise() * method. */ public MatrixOverviewController() { } /** * Initialises the controller class. This method is automatically called * after the fxml file has been loaded. */ @FXML private void initialize() { // Initialise the person table with the two columns. nameColumn.setCellValueFactory(cellData -> cellData.getValue() .nameProperty()); // Not typesafe numRowsColumn .setCellValueFactory(new PropertyValueFactory<Matrix, Integer>( "numRows")); numColsColumn .setCellValueFactory(new PropertyValueFactory<Matrix, Integer>( "numCols")); // Clear matrix details. showMatrixDetails(null); // Listen for selection changes and show the person details when // changed. matrixTable .getSelectionModel() .selectedItemProperty() .addListener( (observable, oldValue, newValue) -> showMatrixDetails(newValue)); } /** * Is called by the main application to give a reference back to itself. * * @param mainApp */ public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; // Add observable list data to the table matrixTable.setItems(mainApp.getMatrixData()); } /** * This method is called when the listener detects that a matrix was selected on the left hand table. * It updates the labels on the right-hand side of the GUI. * @param matrix */ private void showMatrixDetails(Matrix matrix) { if (matrix != null) { nameLabel.setText(matrix.getName()); numRowsLabel.setText(Integer.toString(matrix.getNumRows())); numColsLabel.setText(Integer.toString(matrix.getNumCols())); createdDateLabel.setText(matrix.getCreatedDate().toString()); } else { nameLabel.setText(""); numRowsLabel.setText(""); numColsLabel.setText(""); createdDateLabel.setText(""); } } /** * Called when the user clicks on the new button. * This method will guide the user through the wizard * that asks them to enter the matrix details. */ @FXML private void handleNewMatrix() { // define pages to show Wizard wizard = new Wizard(); wizard.setTitle("Create New Matrix"); int row = 0; GridPane page1Grid = new GridPane(); page1Grid.setVgap(10); page1Grid.setHgap(10); page1Grid.add(new Label("Name:"), 0, row); TextField txFirstName = createTextField("name", 80); page1Grid.add(txFirstName, 1, row++); page1Grid.add(new Label("Number of rows:"), 0, row); TextField txNumRows = createTextField("numRows", 80); page1Grid.add(txNumRows, 1, row++); page1Grid.add(new Label("Number of columns:"), 0, row); TextField txNumCols = createTextField("numCols", 80); page1Grid.add(txNumCols, 1, row); WizardPane page1 = new WizardPane(); page1.setHeaderText("Please Enter Matrix Details"); page1.setContent(page1Grid); final WizardPane page2 = new WizardPane() { @Override public void onEnteringPage(Wizard wizard) { String name = (String) wizard.getSettings().get("name"); // Bit of a horrible hack to get the integers. Need to find // direct conversion. int numRows = Integer.parseInt((String) wizard.getSettings() .get("numRows")); int numCols = Integer.parseInt((String) wizard.getSettings() .get("numCols")); GridPane page2Grid = new GridPane(); for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { // Naming of text fields needs to be improved TextField tx = createTextField("" + i + " " + j, 20); tx.setPromptText("Enter integer"); page2Grid.add(tx,j,i); } } page2Grid.setHgap(5); page2Grid.setVgap(10); setContent(page2Grid); } }; page2.setHeaderText("Creating Matrix"); WizardPane page3 = new WizardPane() { @Override public void onEnteringPage(Wizard wizard) { String name = (String) wizard.getSettings().get("name"); // Bit of a horrible hack to get the integers. Need to find // direct conversion. int numRows = Integer.parseInt((String) wizard.getSettings() .get("numRows")); int numCols = Integer.parseInt((String) wizard.getSettings() .get("numCols")); double[][] data = new double[numRows][numCols]; int currentData; for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { String raw = (String) wizard.getSettings().get("" + i + " " + j); try { currentData = Integer.parseInt(raw); } catch (NumberFormatException e) { currentData = 0; } data[i][j] = currentData; } } mainApp.getMatrixData().add(new Matrix(name, data)); } }; page3.setHeaderText("Goodbye!"); page3.setContentText("Matrix created."); // Example of how to add a button // ButtonType helpDialogButton = new ButtonType("Help", // ButtonData.HELP_2); // page3.getButtonTypes().add(helpDialogButton); // Button helpButton = (Button) page3.lookupButton(helpDialogButton); // helpButton.addEventFilter(ActionEvent.ACTION, actionEvent -> { // actionEvent.consume(); // stop hello.dialog from closing // System.out.println("Help clicked!"); // create wizard wizard.setFlow(new LinearFlow(page1, page2, page3)); // show wizard and wait for response wizard.showAndWait().ifPresent( result -> { if (result == ButtonType.FINISH) { System.out.println("Wizard finished, settings: " + wizard.getSettings()); System.out.println(wizard.getProperties()); } }); } /** * Method is called when the "Delete" button is pressed. * If a valid matrix is selected in the table on the right, * then it is deleted from the matrixTable. */ @FXML private void handleDeleteMatrix() { int selectedIndex = matrixTable.getSelectionModel().getSelectedIndex(); if (selectedIndex >= 0) { matrixTable.getItems().remove(selectedIndex); } else { // Nothing is selected Alert alert = new Alert(AlertType.ERROR); alert.setTitle("No Selection"); alert.setHeaderText("No Matrix Selected"); alert.setContentText("Please select a matrix in the table."); alert.showAndWait(); } } /** * A utility method for creating TextFields with specified id and width. * @param id * @param width * @return */ private TextField createTextField(String id, int width) { TextField textField = new TextField(); textField.setId(id); textField.setPrefWidth(width); GridPane.setHgrow(textField, Priority.ALWAYS); return textField; } }
package file; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; /** * Convenience class for reading text files. Handles file opening, buffering and * closing. */ public class TextFileReader { public String read(File path) throws IOException { FileReader fr = new FileReader(path); String readData = readData(fr); fr.close(); return readData.toString(); } public String read(InputStream is) throws IOException { Reader reader = new InputStreamReader(is); String readData = readData(reader); reader.close(); return readData; } private String readData(Reader reader) throws IOException { BufferedReader br = new BufferedReader(reader); StringBuilder readData = new StringBuilder(); String read; while ((read = br.readLine()) != null) { readData.append(read + "\n"); } readData.deleteCharAt(readData.length() - 1); br.close(); return readData.toString(); } public String read(String path) throws IOException { return read(new File(path)); } }
package me.drton.jmavsim.vehicle; import me.drton.jmavsim.ReportUtil; import me.drton.jmavsim.ReportingObject; import me.drton.jmavsim.Rotor; import me.drton.jmavsim.World; import javax.vecmath.Vector3d; import java.io.FileNotFoundException; /** * Abstract multicopter class. Does all necessary calculations for multirotor with any placement of rotors. * Only rotors on one plane supported now. */ public abstract class AbstractMulticopter extends AbstractVehicle implements ReportingObject { private double dragMove = 0.0; private double dragRotate = 0.0; protected Rotor[] rotors; public AbstractMulticopter(World world, String modelName) throws FileNotFoundException { super(world, modelName); rotors = new Rotor[getRotorsNum()]; for (int i = 0; i < getRotorsNum(); i++) { rotors[i] = new Rotor(); } } public void report(StringBuilder builder) { builder.append("MULTICOPTER"); builder.append(newLine); builder.append("==========="); builder.append(newLine); builder.append(newLine); builder.append("CONTROLS"); builder.append(newLine); builder.append(" builder.append(newLine); if (getControl().size() > 0) { for (int i = 0; i < getControl().size(); i++) { builder.append(Double.toString(getControl().get(i))); builder.append(newLine); } } else { builder.append("n/a"); builder.append(newLine); } builder.append(newLine); for (int i = 0; i < getRotorsNum(); i++) { reportRotor(builder, i); } builder.append(ReportingObject.newLine); builder.append(ReportingObject.newLine); } private void reportRotor(StringBuilder builder, int rotorIndex) { Rotor rotor = rotors[rotorIndex]; builder.append("ROTOR builder.append(rotorIndex); builder.append(newLine); builder.append(" builder.append(newLine); builder.append("Control: "); builder.append(rotor.getControl()); builder.append(newLine); builder.append("Thrust: "); builder.append(rotor.getThrust()); builder.append(" / "); builder.append(rotor.getFullThrust()); builder.append(" [N]"); builder.append(newLine); builder.append("Torque: "); builder.append(rotor.getThrust()); builder.append(" / "); builder.append(rotor.getFullTorque()); builder.append(" [N * m]"); builder.append(newLine); builder.append("Spin up: "); builder.append(rotor.getTimeConstant()); builder.append(" [s]"); builder.append(newLine); builder.append("Position: "); builder.append(ReportUtil.toShortString(getRotorPosition(rotorIndex))); builder.append(newLine); builder.append(newLine); } /** * Get number of rotors. * * @return number of rotors */ protected abstract int getRotorsNum(); /** * Get rotor position relative to gravity center of vehicle. * * @param i rotor number * @return rotor radius-vector from GC */ protected abstract Vector3d getRotorPosition(int i); public void setDragMove(double dragMove) { this.dragMove = dragMove; } public void setDragRotate(double dragRotate) { this.dragRotate = dragRotate; } @Override public void update(long t) { for (Rotor rotor : rotors) { rotor.update(t); } super.update(t); for (int i = 0; i < rotors.length; i++) { double c = control.size() > i ? control.get(i) : 0.0; rotors[i].setControl(c); } } @Override protected Vector3d getForce() { int n = getRotorsNum(); Vector3d f = new Vector3d(); for (int i = 0; i < n; i++) { f.z -= rotors[i].getThrust(); } rotation.transform(f); Vector3d airSpeed = new Vector3d(getVelocity()); airSpeed.scale(-1.0); airSpeed.add(getWorld().getEnvironment().getWind(position)); f.add(getAirFlowForce(airSpeed)); return f; } @Override protected Vector3d getTorque() { int n = getRotorsNum(); Vector3d torque = new Vector3d(); Vector3d m = new Vector3d(); Vector3d t = new Vector3d(); for (int i = 0; i < n; i++) { // Roll / pitch t.z = -rotors[i].getThrust(); m.cross(getRotorPosition(i), t); // Yaw m.z -= rotors[i].getTorque(); torque.add(m); } Vector3d airRotationRate = new Vector3d(rotationRate); airRotationRate.scale(-1.0); torque.add(getAirFlowTorque(airRotationRate)); return torque; } protected Vector3d getAirFlowForce(Vector3d airSpeed) { Vector3d f = new Vector3d(airSpeed); f.scale(f.length() * dragMove); return f; } protected Vector3d getAirFlowTorque(Vector3d airRotationRate) { Vector3d f = new Vector3d(airRotationRate); f.scale(f.length() * dragRotate); return f; } }
package org.bds.lang.expression; import java.util.List; import java.util.Random; import org.antlr.v4.runtime.tree.ParseTree; import org.bds.Config; import org.bds.compile.BdsNodeWalker; import org.bds.compile.CompilerMessage.MessageType; import org.bds.compile.CompilerMessages; import org.bds.lang.BdsNode; import org.bds.lang.statement.Block; import org.bds.lang.statement.Statement; import org.bds.lang.statement.StatementExpr; import org.bds.lang.type.Type; import org.bds.lang.type.Types; import org.bds.lang.value.InterpolateVars; import org.bds.lang.value.Literal; import org.bds.lang.value.LiteralString; import org.bds.symbol.SymbolTable; import org.bds.util.Gpr; import org.bds.util.GprString; /** * A 'task' expression * * @author pcingola */ public class ExpressionTask extends ExpressionWithScope { private static final long serialVersionUID = 5026042355679287158L; // Variable names public static final String TASK_OPTION_CPUS = "cpus"; public static final String TASK_OPTION_MEM = "mem"; public static final String TASK_OPTION_CAN_FAIL = "canFail"; public static final String TASK_OPTION_ALLOW_EMPTY = "allowEmpty"; public static final String TASK_OPTION_NODE = "node"; public static final String TASK_OPTION_PHYSICAL_PATH = "ppwd"; public static final String TASK_OPTION_QUEUE = "queue"; public static final String TASK_OPTION_RETRY = "retry"; public static final String TASK_OPTION_SYSTEM = "system"; public static final String TASK_OPTION_TASKNAME = "taskName"; public static final String TASK_OPTION_TIMEOUT = "timeout"; public static final String TASK_OPTION_WALL_TIMEOUT = "walltimeout"; public static final String CMD_DOWNLOAD = "bds -download"; public static final String CMD_UPLOAD = "bds -upload"; // Note: It is important that 'options' node is type-checked before the others in order to // add variables to the scope before statements uses them. // So the field name should be alphabetically sorted before the other (that's why // I call it 'options' and not 'taskOptions'). // Yes, it's a horrible hack. protected ExpressionTaskOptions options; protected Statement statement; protected boolean asmPushDeps; // True if we must push dependencies to stack (e.g. ExpressionParallel doesn't do it) protected boolean improper; // A task is improper if it has non-sys statements protected InterpolateVars preludeInterpolateVars; // Task prelude: interpolating strings (null if there is nothing to interpolate) protected String preludeStr; // Task prelude (raw) string from config public ExpressionTask(BdsNode parent, ParseTree tree) { super(parent, tree); asmPushDeps = true; } /** * Return a full path to a checkponit file name * The file might be on an Object Store (e.g. S3) * @return */ protected String checkpointFile() { Random r = new Random(); String checkpointFile = getProgramUnit().getFileNameCanonical() + ".task." + id + "." + Math.abs(r.nextInt()) + ".chp"; return checkpointFile; } protected boolean hasPrelude() { return preludeInterpolateVars != null || (preludeStr != null && !preludeStr.isEmpty()); } @Override public boolean isReturnTypesNotNull() { return true; } @Override protected void parse(ParseTree tree) { int idx = 0; idx++; // 'task' keyword // Do we have any task options? if (tree.getChild(idx).getText().equals("(")) { int lastIdx = indexOf(tree, ")"); options = new ExpressionTaskOptions(this, null); options.parse(tree, ++idx, lastIdx); idx = lastIdx + 1; // Skip last ')' } statement = (Statement) factory(tree, idx++); // Parse statement parsePrelude(); } /** * Parse prelude string from bds.config * The "prelude" is a string that is added to all 'sys' within a task */ void parsePrelude() { String prelude = Config.get().getTaskPrelude(); if (prelude == null || prelude.isEmpty()) { preludeStr = ""; return; } preludeInterpolateVars = new InterpolateVars(this, null); if (!preludeInterpolateVars.parse(prelude)) { preludeInterpolateVars = null; // Nothing found? don't bother to keep the object preludeStr = GprString.unescapeDollar(prelude); // Just use literal, but un-escape dollar signs } } /** * Task expression always returns the task id, which is a string */ @Override public Type returnType(SymbolTable symtab) { // Calculate options' return type if (options != null) options.returnType(symtab); if (statement != null) statement.returnType(symtab); // Task expressions return a task ID (a string) returnType = Types.STRING; return returnType; } @Override public void sanityCheck(CompilerMessages compilerMessages) { // Sanity check options if (options != null) options.sanityCheck(compilerMessages); // Sanity check statements if (statement == null) { compilerMessages.add(this, "Task has empty statement", MessageType.ERROR); return; } List<BdsNode> statements = BdsNodeWalker.findNodes(statement, null, true, false); // No child nodes? Add the only node we have if (statements.isEmpty()) statements.add(statement); setImproper(statements); } /** * An "improper" task is a task that anything other than 'sys' statement/s * Improper tasks are executed by creating a checkpoint and restoring from the checkpoint */ protected void setImproper(List<BdsNode> statements) { improper = false; for (BdsNode node : statements) { if (node instanceof Statement) { boolean ok = node instanceof ExpressionSys || node instanceof Block || node instanceof Literal || node instanceof InterpolateVars || node instanceof Reference || node instanceof StatementExpr ; // if (!ok) compilerMessages.add(this, "Only sys statements are allowed in a task (line " + node.getLineNum() + ")", MessageType.ERROR); if (!ok) improper = true; } } } @Override public String toAsm() { StringBuilder sb = new StringBuilder(); sb.append(super.toAsmNode()); // Task will use the node to get parameters sb.append("scopepush\n"); // Define labels String labelEnd = baseLabelName() + "end"; String labelFalse = baseLabelName() + "false"; // Options sb.append(toAsmOptions(labelFalse)); // Command (e.g. task and statements) sb.append(toAsmCmd(labelEnd)); // Task expression not evaluated because one or more bool expressions was false sb.append(labelFalse + ":\n"); sb.append("pushs ''\n"); // Task not executed, push an empty task id // End of task expression sb.append(labelEnd + ":\n"); sb.append("scopepop\n"); return sb.toString(); } /** * Commands (i.e. task) */ protected String toAsmCmd(String labelEnd) { StringBuilder sb = new StringBuilder(); if (hasPrelude()) sb.append(toAsmPrelude()); sb.append(toAsmStatements()); // Statements (e.g.: sys commands) if (hasPrelude()) sb.append("adds\n"); sb.append("task\n"); sb.append("jmp " + labelEnd + "\n"); // Go to the end return sb.toString(); } /** * Options */ protected String toAsmOptions(String labelFalse) { StringBuilder sb = new StringBuilder(); if (options != null) { sb.append(options.toAsm(labelFalse, asmPushDeps)); // Jump to 'labelFalse' if any of the bool expressions is false } else if (asmPushDeps) { // No options or dependencies. // Add empty list as dependency sb.append("new string[]\n"); sb.append("new string[]\n"); } return sb.toString(); } protected String toAsmPrelude() { if (preludeInterpolateVars != null) return preludeInterpolateVars.toAsm(); if (preludeStr != null && !preludeStr.isEmpty()) return "pushs " + preludeStr + "\n"; return ""; } protected String toAsmStatements() { return improper ? toAsmStatementsImproper() : toAsmStatementsProper(); } /** * Create a checkpoint and create a task to execute from that checkpoint * 'sys' opcodes are transformed into 'shell' */ protected String toAsmStatementsImproper() { StringBuilder sb = new StringBuilder(); // Store the input / output dependencies to a hidden variable name // These were pushed into the stack in the previous step String varInputs = baseVarName() + "inputs"; String varOutputs = baseVarName() + "outputs"; sb.append("varpop " + varInputs + "\n"); sb.append("varpop " + varOutputs + "\n"); // Create a checkpoint String labelTaskBodyEnd = baseLabelName() + "body_end"; String checkpointFile = checkpointFile(); sb.append("pushs '" + checkpointFile + "'\n"); sb.append("checkpoint\n"); sb.append("checkpoint_recovered\n"); sb.append("jmpf " + labelTaskBodyEnd + "\n"); // Task body (i.e. the statements in the task) are executed by the process that recovers from the checkpoint sb.append(toAsmStatementsImproperTaskBody(varOutputs, varInputs)); // This is the task sb.append(labelTaskBodyEnd + ":\n"); sb.append("load " + varOutputs + "\n"); sb.append("load " + varInputs + "\n"); sb.append("pushs 'bds -r " + checkpointFile + "'\n"); return sb.toString(); } /** * This method creates the code from the statements of an improper task * * E.g. An improper task is executed in a cluster: * - A checkpoint is created * - A job is submitted to the cluster to run bds recovering from that checkpoint * - When the node executes bds, it recovers the checkpoint and executes the statement within the task */ protected String toAsmStatementsImproperTaskBody(String varOutputs, String varInputs) { StringBuilder sb = new StringBuilder(); Block block = (Block) statement; for (Statement st : block.getStatements()) { sb.append(st.toAsm()); } // There is an implicit 'exit' in the block. // Remember that these statement are executed in another process or another host, so // there is no point to continue beyond the task statements (that part is executed // on the main bds process) sb.append("pushi 0\n"); sb.append("halt\n"); return sb.toString(); } /** * Evaluate 'sys' statements used to create task */ protected String toAsmStatementsProper() { // Only one 'sys' expression if (statement instanceof StatementExpr) { Expression exprSys = ((StatementExpr) statement).getExpression(); ExpressionSys sys = (ExpressionSys) exprSys; return sys.toAsm(false); } // One 'sys' expression within a statement if (statement instanceof ExpressionSys) { ExpressionSys sys = (ExpressionSys) statement; return sys.toAsm(false); } // Multiple 'sys' expressions in a block if (statement instanceof Block) { // Create one sys statement for all sys statements in the block StringBuilder sb = new StringBuilder(); Block block = (Block) statement; sb.append("new string\n"); for (Statement st : block.getStatements()) { // Get 'sys' expression if (st instanceof StatementExpr) st = ((StatementExpr) st).getExpression(); ExpressionSys sys = (ExpressionSys) st; sb.append(sys.toAsm(false)); sb.append("adds\n"); } return sb.toString(); } throw new RuntimeException("Unimplemented for class '" + statement.getClass().getSimpleName() + "'"); } @Override public String toString() { return "task" + (options != null ? options : "") + " " + toStringStatement() ; } /** * Format statements */ protected String toStringStatement() { if (statement instanceof LiteralString) { // Compact single line return ((LiteralString) statement).getValue().asString().trim(); } if (statement instanceof ExpressionSys || statement instanceof StatementExpr) { // Compact single line form return statement.toString(); } // Multi-line return "{\n" + Gpr.prependEachLine("\t", statement.toString()) + "}" ; } @Override public void typeCheck(SymbolTable symtab, CompilerMessages compilerMessages) { returnType(symtab); if (options != null) options.typeCheck(symtab, compilerMessages); if (statement != null) statement.typeCheck(symtab, compilerMessages); } }
package de.jungblut.classification.nn; import gnu.trove.list.array.TDoubleArrayList; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import com.google.common.base.Preconditions; import de.jungblut.math.DoubleVector; import de.jungblut.math.dense.DenseDoubleMatrix; import de.jungblut.math.dense.DenseDoubleVector; import de.jungblut.math.minimize.DenseMatrixFolder; import de.jungblut.math.minimize.Fmincg; import de.jungblut.writable.MatrixWritable; import de.jungblut.writable.VectorWritable; /** * Multilayer perceptron by my collegue Marvin Ritter using my math library. <br/> * I have changed it to a format that can be used for batch training for example * in a clustered environment.<br/> * Error function is the mean squared error and activation function in each * neuron is the sigmoid function. * * @author marvin.ritter * @author thomas.jungblut * */ public final class MultilayerPerceptron { private final WeightMatrix[] weights; private final Layer[] layers; /** * Multilayer perceptron initializer by using an int[] to describe the number * of units per layer.<br/> * For example if you want to solve the XOR problem by 2 input neurons, a * hidden layer with 3 neurons and an output layer with one neuron, you can * feed this contructor with int[]{2,3,1}. */ public MultilayerPerceptron(int[] layer) { this.layers = new Layer[layer.length]; for (int i = 0; i < layer.length; i++) { layers[i] = new Layer(layer[i]); } weights = new WeightMatrix[layers.length - 1]; for (int i = 0; i < weights.length; i++) { weights[i] = new WeightMatrix(layers[i], layers[i + 1]); } } /** * Custom serialization constructor for already trained networks. */ public MultilayerPerceptron(Layer[] layers, WeightMatrix[] weights) { this.layers = layers; this.weights = weights; } /** * Predicts the outcome of the given input by doing a forward pass. */ public DenseDoubleVector predict(DoubleVector xi) { layers[0].setActivations(xi); for (WeightMatrix weight : weights) { weight.forward(); } return layers[layers.length - 1].getActivations(); } /** * At the beginning of each batch forward propagation we should reset the * gradients. */ public void resetGradients() { // reset all gradients / derivatives for (WeightMatrix weight : weights) { weight.resetDerivatives(); } } /** * Do a forward step and calculate the difference between the outcome and the * prediction. */ public DoubleVector forwardStep(DoubleVector x, DoubleVector outcome) { DenseDoubleVector prediction = predict(x); return prediction.subtract(outcome); } /** * Do a backward step by the given error in the last layer. */ public void backwardStep(DoubleVector errorLastLayer) { // set error of last layer and then use backward propagation the calculate // the errors of the other layers // the first layer can be left out, cause the input error is not wrong ;) layers[layers.length - 1].setErrors(errorLastLayer); for (int k = weights.length - 1; k > 0; k weights[k].backwardError(); } // based on the errors we can now calculate the partial derivatives for all // layers and add them to the // internal matrix for (WeightMatrix weight : weights) { weight.addDerivativesFromError(); } } /** * After a full forward and backward step we can adjust the weights by * normalizing the via the learningrate and lambda. Here we also need the * number of training examples seen.<br/> */ public void adjustWeights(int numTrainingExamples, double learningRate, double lambda) { // adjust weights using the given learning rate for (WeightMatrix weight : weights) { weight.updateWeights(numTrainingExamples, learningRate, lambda); } } /** * Full backpropagation training method. It checks whether the maximum * iterations have been exceeded or a given error has been archived. * * @param x the training examples * @param y the outcomes for the training examples * @param maxIterations the number of maximum iterations to train * @param maximumError the maximum error when training can be stopped * @param learningRate the given learning rate * @param lambda the given regularization parameter * @param verbose output to console with the last given errors * @return the squared mean errors per iteration, can be used to plot learning * curves */ public DoubleVector train(DoubleVector[] x, DoubleVector[] y, int maxIterations, double maximumError, double learningRate, double lambda, boolean verbose) { TDoubleArrayList errorList = new TDoubleArrayList(); int iteration = 0; while (iteration < maxIterations) { double mse = 0.0d; resetGradients(); for (int i = 0; i < x.length; i++) { DoubleVector difference = forwardStep(x[i], y[i]); mse += difference.pow(2).sum(); backwardStep(difference); } adjustWeights(x.length, learningRate, lambda); if (verbose) { System.out.println(iteration + ": " + mse); } errorList.add(mse); iteration++; // stop learning if we have reached our maximum error. if (mse < maximumError) break; } return new DenseDoubleVector(errorList.toArray()); } /** * Full backpropagation training method. It performs weight finding by using * fmincg (conjugate gradient). <b>It currently only works for three layered * neural networks (input, hidden, output).</b> * * @param x the training examples. * @param y the outcomes for the training examples. * @param maxIterations the number of maximum iterations to train. * @param lambda the given regularization parameter. * @param verbose output to console with the last given errors. * @return the cost of the training. */ public double trainFmincg(DenseDoubleMatrix x, DenseDoubleMatrix y, int maxIterations, double lambda, boolean verbose) { Preconditions.checkArgument(getLayers().length == 3); DenseDoubleVector pInput = DenseMatrixFolder.foldMatrices( getWeights()[0].getWeights(), getWeights()[1].getWeights()); MultilayerPerceptronCostFunction costFunction = new MultilayerPerceptronCostFunction( this, x, y, lambda); DoubleVector minimizeFunction = Fmincg.minimizeFunction(costFunction, pInput, maxIterations, verbose); DenseDoubleMatrix[] unfoldMatrices = DenseMatrixFolder.unfoldMatrices( minimizeFunction, new int[][] { { getWeights()[0].getWeights().getRowCount(), getWeights()[0].getWeights().getColumnCount() }, { getWeights()[1].getWeights().getRowCount(), getWeights()[1].getWeights().getColumnCount() } }); getWeights()[0].setWeights(unfoldMatrices[0]); getWeights()[1].setWeights(unfoldMatrices[1]); return costFunction.evaluateCost(minimizeFunction).getFirst(); } public WeightMatrix[] getWeights() { return weights; } public Layer[] getLayers() { return layers; } public static MultilayerPerceptron deserialize(DataInput in) throws IOException { int numLayers = in.readInt(); Layer[] layers = new Layer[numLayers]; for (int i = 0; i < numLayers; i++) { int layerLength = in.readInt(); DoubleVector activations = VectorWritable.readVector(in); DoubleVector errors = VectorWritable.readVector(in); layers[i] = new Layer(layerLength, (DenseDoubleVector) activations, (DenseDoubleVector) errors); } WeightMatrix[] weights = new WeightMatrix[numLayers - 1]; for (int i = 0; i < weights.length; i++) { DenseDoubleMatrix derivatives = (DenseDoubleMatrix) MatrixWritable .read(in); DenseDoubleMatrix weightMatrix = (DenseDoubleMatrix) MatrixWritable .read(in); weights[i] = new WeightMatrix(layers[i], layers[i + 1], weightMatrix, derivatives); } return new MultilayerPerceptron(layers, weights); } public static void serialize(MultilayerPerceptron model, DataOutput out) throws IOException { out.writeInt(model.layers.length); // first write all the layers for (Layer l : model.layers) { out.writeInt(l.getLength()); VectorWritable.writeVector(l.getActivations(), out); VectorWritable.writeVector(l.getErrors(), out); } // write the weight matrices for (WeightMatrix mat : model.weights) { DenseDoubleMatrix derivatives = mat.getDerivatives(); MatrixWritable.write(derivatives, out); DenseDoubleMatrix weights = mat.getWeights(); MatrixWritable.write(weights, out); } } }
package org.beanmaker.util; import org.dbbeans.util.Strings; import org.jcodegen.html.ATag; import org.jcodegen.html.InputTag; import org.jcodegen.html.OptionTag; import org.jcodegen.html.SelectTag; import org.jcodegen.html.SpanTag; import org.jcodegen.html.TableTag; import org.jcodegen.html.Tag; import org.jcodegen.html.TbodyTag; import org.jcodegen.html.TdTag; import org.jcodegen.html.ThTag; import org.jcodegen.html.TheadTag; import org.jcodegen.html.TrTag; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.util.List; public abstract class BaseMasterTableView extends BaseView { protected final String tableId; protected String tableCssClass = "cctable"; protected String thResetCssClass = null; protected String tdResetCssClass = null; protected String thFilterCssClass = null; protected String tdFilterCssClass = null; protected String thTitleCssClass = "tb-sort"; protected String formElementFilterCssClass = "tb-filter"; protected String removeFilteringLinkCssClass = "tb-nofilter"; protected Tag removeFilteringHtmlTags = new SpanTag().cssClass("glyphicon glyphicon-remove").title("Remove Filtering"); protected String yesName = "yes"; protected String noName = "no"; protected String yesValue = "A"; protected String noValue = "Z"; protected String yesDisplay = ""; protected String noDisplay = ""; protected DateFormat dateFormat = null; protected DateFormat timeFormat = null; protected DateFormat datetimeFormat = null; protected String booleanCenterValueCssClass = "center"; protected int zeroFilledMaxDigits = 20; protected boolean displayId = false; public BaseMasterTableView(final String resourceBundleName, final String tableId) { super(resourceBundleName); this.tableId = tableId; } public String getMasterTable() { return getTable().child(getHead()).child(getBody()).toString(); } protected TableTag getTable() { return new TableTag().cssClass(tableCssClass).id(tableId); } protected TheadTag getHead() { final TheadTag head = new TheadTag(); head.child(getFilterRow()); head.child(getTitleRow()); return head; } protected TbodyTag getBody() { final TbodyTag body = new TbodyTag(); for (TrTag tr: getData()) body.child(tr); return body; } protected abstract List<TrTag> getData(); protected TrTag getFilterRow() { return new TrTag().child(getRemoveFilteringCellWithLink()); } protected TrTag getTitleRow() { return new TrTag().child(getRemoveFilteringCell()); } protected ThTag getRemoveFilteringCellWithLink() { return getRemoveFilteringCell().child( new ATag().href("#").cssClass(removeFilteringLinkCssClass).child(removeFilteringHtmlTags) ); } protected ThTag getRemoveFilteringCell() { final ThTag cell = new ThTag(); if (thResetCssClass != null) cell.cssClass(thResetCssClass); return cell; } protected ThTag getTableFilterCell() { final ThTag cell = new ThTag(); if (thFilterCssClass != null) cell.cssClass(thFilterCssClass); return cell; } protected ThTag getStringFilterCell(final String name) { return getTableFilterCell().child( new InputTag(InputTag.InputType.TEXT).name("tb-" + name).cssClass(formElementFilterCssClass).attribute("autocomplete", "off") ); } protected ThTag getBooleanFilterCell(final String name) { return getTableFilterCell().child( new SelectTag().name(name).cssClass(formElementFilterCssClass).child( new OptionTag("", "").selected() ).child( new OptionTag(yesName, yesValue) ).child( new OptionTag(noName, noValue) ) ); } protected ThTag getTitleCell(final String name) { return getTitleCell(name, resourceBundle.getString(name)); } protected ThTag getTitleCell(final String name, final String adhocTitle) { return new ThTag(adhocTitle).cssClass(thTitleCssClass).attribute("data-sort-class", "tb-" + name); } protected TrTag getTableLine() { final TrTag line = new TrTag(); line.child(getTableCellForRemoveFilteringPlaceholder()); return line; } protected TdTag getTableCellForRemoveFilteringPlaceholder() { final TdTag cell = new TdTag(); if (tdResetCssClass != null) cell.cssClass(tdResetCssClass); return cell; } protected TdTag getTableCell(final String name, final String value) { return new TdTag(value).cssClass("tb-" + name); } protected TdTag getTableCell(final String name, final Date value) { if (dateFormat == null) dateFormat = DateFormat.getDateInstance(); return getTableCell(name, dateFormat.format(value)).attribute("data-sort-value", value.toString()); } protected TdTag getTableCell(final String name, final Time value) { if (timeFormat == null) timeFormat = DateFormat.getTimeInstance(); return getTableCell(name, timeFormat.format(value)).attribute("data-sort-value", value.toString()); } protected TdTag getTableCell(final String name, final Timestamp value) { if (datetimeFormat == null) datetimeFormat = DateFormat.getDateTimeInstance(); return getTableCell(name, datetimeFormat.format(value)).attribute("data-sort-value", value.toString()); } protected TdTag getTableCell(final String name, final boolean value) { if (value) return getTableBooleanCell(name, yesDisplay, yesValue); return getTableBooleanCell(name, noDisplay, noValue); } protected TdTag getTableBooleanCell(final String name, final String value, final String sortnfilter) { return new TdTag(value).cssClass(booleanCenterValueCssClass + " tb-" + name) .attribute("data-filter-value", sortnfilter).attribute("data-sort-value", sortnfilter); } protected TdTag getTableCell(final String name, final long value) { return getTableCell(name, Long.toString(value)).attribute("data-sort-value", Strings.zeroFill(value, zeroFilledMaxDigits)); } }
package org.eclipse.imp.pdb.facts.util; import static org.eclipse.imp.pdb.facts.util.AbstractSpecialisedImmutableMap.entryOf; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndInsert; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndInsertPair; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndMoveToBackPair; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndMoveToFrontPair; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndRemove; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndRemovePair; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndSet; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("rawtypes") public class TrieMap<K, V> extends AbstractImmutableMap<K, V> { @SuppressWarnings("unchecked") private static final TrieMap EMPTY_INPLACE_INDEX_MAP = new TrieMap( CompactNode.EMPTY_INPLACE_INDEX_NODE, 0, 0); private final AbstractNode<K, V> rootNode; private final int hashCode; private final int cachedSize; TrieMap(AbstractNode<K, V> rootNode, int hashCode, int cachedSize) { this.rootNode = rootNode; this.hashCode = hashCode; this.cachedSize = cachedSize; assert invariant(); } @SuppressWarnings("unchecked") public static final <K, V> ImmutableMap<K, V> of() { return TrieMap.EMPTY_INPLACE_INDEX_MAP; } @SuppressWarnings("unchecked") public static final <K, V> ImmutableMap<K, V> of(Object... keyValuePairs) { if (keyValuePairs.length % 2 != 0) { throw new IllegalArgumentException( "Length of argument list is uneven: no key/value pairs."); } ImmutableMap<K, V> result = TrieMap.EMPTY_INPLACE_INDEX_MAP; for (int i = 0; i < keyValuePairs.length; i += 2) { final K key = (K) keyValuePairs[i]; final V val = (V) keyValuePairs[i+1]; result = result.__put(key, val); } return result; } @SuppressWarnings("unchecked") public static final <K, V> TransientMap<K, V> transientOf() { return TrieMap.EMPTY_INPLACE_INDEX_MAP.asTransient(); } @SuppressWarnings("unchecked") public static final <K, V> TransientMap<K, V> transientOf(Object... keyValuePairs) { if (keyValuePairs.length % 2 != 0) { throw new IllegalArgumentException( "Length of argument list is uneven: no key/value pairs."); } final TransientMap<K, V> result = TrieMap.EMPTY_INPLACE_INDEX_MAP.asTransient(); for (int i = 0; i < keyValuePairs.length; i += 2) { final K key = (K) keyValuePairs[i]; final V val = (V) keyValuePairs[i+1]; result.__put(key, val); } 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, V> it = keyIterator(); it.hasNext();) { final K key = it.next(); final V val = it.get(); _hash += key.hashCode() ^ val.hashCode(); _count += 1; } return this.hashCode == _hash && this.cachedSize == _count; } @Override public TrieMap<K, V> __put(K k, V v) { return __putEquivalent(k, v, equalityComparator()); } @Override public TrieMap<K, V> __putEquivalent(K key, V val, Comparator<Object> cmp) { final int keyHash = key.hashCode(); final Result<K, V, ? extends AbstractNode<K, V>> result = rootNode.updated(null, key, keyHash, val, 0, cmp); if (result.isModified()) { if (result.hasReplacedValue()) { final int valHashOld = result.getReplacedValue().hashCode(); final int valHashNew = val.hashCode(); return new TrieMap<K, V>(result.getNode(), hashCode + (keyHash ^ valHashNew) - (keyHash ^ valHashOld), cachedSize); } final int valHash = val.hashCode(); return new TrieMap<K, V>(result.getNode(), hashCode + (keyHash ^ valHash), cachedSize + 1); } return this; } @Override public ImmutableMap<K, V> __putAll(Map<? extends K, ? extends V> map) { return __putAllEquivalent(map, equalityComparator()); } @Override public ImmutableMap<K, V> __putAllEquivalent(Map<? extends K, ? extends V> map, Comparator<Object> cmp) { TransientMap<K, V> tmp = asTransient(); tmp.__putAllEquivalent(map, cmp); return tmp.freeze(); } @Override public TrieMap<K, V> __remove(K k) { return __removeEquivalent(k, equalityComparator()); } @Override public TrieMap<K, V> __removeEquivalent(K key, Comparator<Object> cmp) { final int keyHash = key.hashCode(); final Result<K, V, ? extends AbstractNode<K, V>> 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(); final int valHash = rootNode.findByKey(key, keyHash, 0, cmp).get().getValue() .hashCode(); return new TrieMap<K, V>(result.getNode(), hashCode - (keyHash ^ valHash), cachedSize - 1); } return this; } @Override public boolean containsKey(Object o) { return rootNode.containsKey(o, o.hashCode(), 0, equalityComparator()); } @Override public boolean containsKeyEquivalent(Object o, Comparator<Object> cmp) { return rootNode.containsKey(o, o.hashCode(), 0, cmp); } @Override public boolean containsValue(Object o) { return containsValueEquivalent(o, equalityComparator()); } @Override public boolean containsValueEquivalent(Object o, Comparator<Object> cmp) { for (Iterator<V> iterator = valueIterator(); iterator.hasNext();) { if (cmp.compare(iterator.next(), o) == 0) { return true; } } return false; } @Override public V get(Object key) { return getEquivalent(key, equalityComparator()); } @Override public V getEquivalent(Object key, Comparator<Object> cmp) { final Optional<Map.Entry<K, V>> result = rootNode.findByKey(key, key.hashCode(), 0, cmp); if (result.isPresent()) { return result.get().getValue(); } else { return null; } } @Override public int size() { return cachedSize; } @Override public SupplierIterator<K, V> keyIterator() { return new TrieMapIteratorWithFixedWidthStack<>(rootNode); } @Override public Iterator<V> valueIterator() { return new TrieMapValueIterator<>(new TrieMapIteratorWithFixedWidthStack<>(rootNode)); } @Override public Iterator<Map.Entry<K, V>> entryIterator() { return new TrieMapEntryIterator<>(new TrieMapIteratorWithFixedWidthStack<>(rootNode)); } @Override public Set<java.util.Map.Entry<K, V>> entrySet() { Set<java.util.Map.Entry<K, V>> entrySet = null; if (entrySet == null) { entrySet = new AbstractSet<java.util.Map.Entry<K, V>>() { @Override public Iterator<java.util.Map.Entry<K, V>> iterator() { return new Iterator<Entry<K, V>>() { private final Iterator<Entry<K, V>> i = entryIterator(); @Override public boolean hasNext() { return i.hasNext(); } @Override public Entry<K, V> next() { return i.next(); } @Override public void remove() { i.remove(); } }; } @Override public int size() { return TrieMap.this.size(); } @Override public boolean isEmpty() { return TrieMap.this.isEmpty(); } @Override public void clear() { TrieMap.this.clear(); } @Override public boolean contains(Object k) { return TrieMap.this.containsKey(k); } }; } return entrySet; } private static class TrieMapIteratorWithFixedWidthStack<K, V> implements SupplierIterator<K, V> { int valueIndex; int valueLength; AbstractNode<K, V> valueNode; V lastValue = null; int stackLevel; int[] indexAndLength = new int[7 * 2]; @SuppressWarnings("unchecked") AbstractNode<K, V>[] nodes = new AbstractNode[7]; TrieMapIteratorWithFixedWidthStack(AbstractNode<K, V> 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 AbstractNode<K, V> nextNode = nodes[stackLevel].getNode(nodeIndex); indexAndLength[2 * stackLevel] = (nodeIndex + 1); final int nextNodePayloadArity = 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 (nextNodePayloadArity != 0) { valueNode = nextNode; valueIndex = 0; valueLength = nextNodePayloadArity; 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 = valueNode.getValue(valueIndex); valueIndex += 1; return lastKey; } } @Override public V get() { if (lastValue == null) { throw new NoSuchElementException(); } else { V tmp = lastValue; lastValue = null; return tmp; } } @Override public void remove() { throw new UnsupportedOperationException(); } } /* * TODO/NOTE: This iterator is also reused by the TransientTrieMap. */ private static class TrieMapEntryIterator<K, V> implements Iterator<Map.Entry<K, V>> { private final SupplierIterator<K, V> iterator; TrieMapEntryIterator(SupplierIterator<K, V> iterator) { this.iterator = iterator; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Map.Entry<K, V> next() { final K key = iterator.next(); final V val = iterator.get(); return entryOf(key, val); } @Override public void remove() { iterator.remove(); } } /* * TODO/NOTE: This iterator is also reused by the TransientTrieMap. */ private static class TrieMapValueIterator<K, V> implements Iterator<V> { private final SupplierIterator<K, V> iterator; TrieMapValueIterator(SupplierIterator<K, V> iterator) { this.iterator = iterator; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public V next() { iterator.next(); return iterator.get(); } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public boolean isTransientSupported() { return true; } @Override public TransientMap<K, V> asTransient() { return new TransientTrieMap<K, V>(this); } static final class TransientTrieMap<K, V> extends AbstractMap<K, V> implements TransientMap<K, V> { final private AtomicReference<Thread> mutator; private AbstractNode<K, V> rootNode; private int hashCode; private int cachedSize; TransientTrieMap(TrieMap<K, V> trieMap) { this.mutator = new AtomicReference<Thread>(Thread.currentThread()); this.rootNode = trieMap.rootNode; this.hashCode = trieMap.hashCode; this.cachedSize = trieMap.cachedSize; assert invariant(); } // TODO: merge with TrieMap invariant (as function) private boolean invariant() { int _hash = 0; for (SupplierIterator<K, V> it = keyIterator(); it.hasNext();) { final K key = it.next(); final V val = it.get(); _hash += key.hashCode() ^ val.hashCode(); } return this.hashCode == _hash; } @Override public boolean containsKey(Object o) { return rootNode.containsKey(o, o.hashCode(), 0, equalityComparator()); } @Override public boolean containsKeyEquivalent(Object o, Comparator<Object> cmp) { return rootNode.containsKey(o, o.hashCode(), 0, cmp); } @Override public V get(Object key) { return getEquivalent(key, equalityComparator()); } @Override public V getEquivalent(Object key, Comparator<Object> cmp) { final Optional<Map.Entry<K, V>> result = rootNode .findByKey(key, key.hashCode(), 0, cmp); if (result.isPresent()) { return result.get().getValue(); } else { return null; } } @Override public V __put(K k, V v) { return __putEquivalent(k, v, equalityComparator()); } @Override public V __putEquivalent(K key, V val, Comparator<Object> cmp) { if (mutator.get() == null) { throw new IllegalStateException("Transient already frozen."); } final int keyHash = key.hashCode(); final Result<K, V, ? extends AbstractNode<K, V>> result = rootNode.updated(mutator, key, keyHash, val, 0, cmp); if (result.isModified()) { rootNode = result.getNode(); if (result.hasReplacedValue()) { final V old = result.getReplacedValue(); final int valHashOld = old.hashCode(); final int valHashNew = val.hashCode(); hashCode += keyHash ^ valHashNew; hashCode -= keyHash ^ valHashOld; // cachedSize remains same assert invariant(); return old; } else { final int valHashNew = val.hashCode(); hashCode += keyHash ^ valHashNew; cachedSize += 1; assert invariant(); return null; } } assert invariant(); return null; } @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, V, ? extends AbstractNode<K, V>> 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(); final int valHash = rootNode.findByKey(key, keyHash, 0, cmp).get().getValue() .hashCode(); rootNode = result.getNode(); hashCode -= keyHash ^ valHash; cachedSize -= 1; assert invariant(); return true; } assert invariant(); return false; } @Override public boolean __putAll(Map<? extends K, ? extends V> map) { return __putAllEquivalent(map, equalityComparator()); } @Override public boolean __putAllEquivalent(Map<? extends K, ? extends V> map, Comparator<Object> cmp) { boolean modified = false; for (Entry<? extends K, ? extends V> entry : map.entrySet()) { final boolean isPresent = containsKeyEquivalent(entry.getKey(), cmp); final V replaced = __putEquivalent(entry.getKey(), entry.getValue(), cmp); if (!isPresent || replaced != null) { modified = true; } } return modified; } @Override public Set<java.util.Map.Entry<K, V>> entrySet() { Set<java.util.Map.Entry<K, V>> entrySet = null; if (entrySet == null) { entrySet = new AbstractSet<java.util.Map.Entry<K, V>>() { @Override public Iterator<java.util.Map.Entry<K, V>> iterator() { return new Iterator<Entry<K, V>>() { private final Iterator<Entry<K, V>> i = entryIterator(); @Override public boolean hasNext() { return i.hasNext(); } @Override public Entry<K, V> next() { return i.next(); } @Override public void remove() { i.remove(); } }; } @Override public int size() { return TransientTrieMap.this.size(); } @Override public boolean isEmpty() { return TransientTrieMap.this.isEmpty(); } @Override public void clear() { TransientTrieMap.this.clear(); } @Override public boolean contains(Object k) { return TransientTrieMap.this.containsKey(k); } }; } return entrySet; } @Override public SupplierIterator<K, V> keyIterator() { return new TransientTrieMapIterator<K, V>(this); } @Override public Iterator<V> valueIterator() { return new TrieMapValueIterator<>(keyIterator()); } @Override public Iterator<Map.Entry<K, V>> entryIterator() { return new TrieMapEntryIterator<>(keyIterator()); } /** * Iterator that first iterates over inlined-values and then continues * depth first recursively. */ // TODO: test private static class TransientTrieMapIterator<K, V> extends TrieMapIteratorWithFixedWidthStack<K, V> { final TransientTrieMap<K, V> transientTrieMap; K lastKey; TransientTrieMapIterator(TransientTrieMap<K, V> transientTrieMap) { super(transientTrieMap.rootNode); this.transientTrieMap = transientTrieMap; } @Override public K next() { lastKey = super.next(); return lastKey; } @Override public void remove() { transientTrieMap.__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 ImmutableMap<K, V> freeze() { if (mutator.get() == null) { throw new IllegalStateException("Transient already frozen."); } mutator.set(null); return new TrieMap<K, V>(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 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> comparator); abstract Optional<Map.Entry<K, V>> findByKey(Object key, int hash, int shift); abstract Optional<Map.Entry<K, V>> findByKey(Object key, int hash, int shift, Comparator<Object> cmp); abstract Result<K, V, ? extends AbstractNode<K, V>> updated( AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift); abstract Result<K, V, ? extends AbstractNode<K, V>> updated( AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp); abstract Result<K, V, ? extends AbstractNode<K, V>> removed( AtomicReference<Thread> mutator, K key, int hash, int shift); abstract Result<K, V, ? extends AbstractNode<K, V>> removed( AtomicReference<Thread> mutator, K key, int hash, 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 V getValue(int index); abstract AbstractNode<K, V> getNode(int index); abstract boolean hasNodes(); abstract Iterator<? extends AbstractNode<K, V>> nodeIterator(); abstract int nodeArity(); abstract boolean hasPayload(); abstract SupplierIterator<K, V> 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, V> it = new TrieMapIteratorWithFixedWidthStack<>(this); int size = 0; while (it.hasNext()) { size += 1; it.next(); } return size; } } private static abstract class CompactNode<K, V> extends AbstractNode<K, V> { static final byte SIZE_EMPTY = 0b00; static final byte SIZE_ONE = 0b01; static final byte SIZE_MORE_THAN_ONE = 0b10; @Override abstract Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift); @Override abstract Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp); @Override abstract Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int hash, int shift); @Override abstract Result<K, V, ? extends CompactNode<K, V>> 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(); /** * Returns the first value stored within this node. * * @return first value */ abstract V headVal(); 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 CompactNode EMPTY_INPLACE_INDEX_NODE = new Value0Index0Node(null); static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos, CompactNode<K, V> 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, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator) { return EMPTY_INPLACE_INDEX_NODE; } // manually added static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2, byte npos3, CompactNode<K, V> node3, byte npos4, CompactNode<K, V> node4) { final int bitmap = (1 << pos1) | (1 << npos1) | (1 << npos2) | (1 << npos3) | (1 << npos4); final int valmap = (1 << pos1); return new MixedIndexNode<>(mutator, bitmap, valmap, new Object[] { key1, val1, node1, node2, node3, node4 }, (byte) 1); } // manually added static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte pos3, K key3, V val3, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> 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 MixedIndexNode<>(mutator, bitmap, valmap, new Object[] { key1, val1, key2, val2, key3, val3, node1, node2 }, (byte) 3); } // manually added static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2, byte npos3, CompactNode<K, V> node3) { final int bitmap = (1 << pos1) | (1 << pos2) | (1 << npos1) | (1 << npos2) | (1 << npos3); final int valmap = (1 << pos1) | (1 << pos2); return new MixedIndexNode<>(mutator, bitmap, valmap, new Object[] { key1, val1, key2, val2, node1, node2, node3 }, (byte) 2); } // manually added static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte pos3, K key3, V val3, byte pos4, K key4, V val4, byte npos1, CompactNode<K, V> 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 MixedIndexNode<>(mutator, bitmap, valmap, new Object[] { key1, val1, key2, val2, key3, val3, key4, val4, node1 }, (byte) 4); } // manually added static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte pos3, K key3, V val3, byte pos4, K key4, V val4, byte pos5, K key5, V val5) { final int valmap = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << pos4) | (1 << pos5); return new MixedIndexNode<>(mutator, valmap, valmap, new Object[] { key1, val1, key2, val2, key3, val3, key4, val4, key5, val5 }, (byte) 5); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2) { return new Value0Index2Node<>(mutator, npos1, node1, npos2, node2); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2, byte npos3, CompactNode<K, V> node3) { return new Value0Index3Node<>(mutator, npos1, node1, npos2, node2, npos3, node3); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2, byte npos3, CompactNode<K, V> node3, byte npos4, CompactNode<K, V> node4) { return new Value0Index4Node<>(mutator, npos1, node1, npos2, node2, npos3, node3, npos4, node4); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1) { return new Value1Index0Node<>(mutator, pos1, key1, val1); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte npos1, CompactNode<K, V> node1) { return new Value1Index1Node<>(mutator, pos1, key1, val1, npos1, node1); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2) { return new Value1Index2Node<>(mutator, pos1, key1, val1, npos1, node1, npos2, node2); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2, byte npos3, CompactNode<K, V> node3) { return new Value1Index3Node<>(mutator, pos1, key1, val1, npos1, node1, npos2, node2, npos3, node3); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2) { return new Value2Index0Node<>(mutator, pos1, key1, val1, pos2, key2, val2); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte npos1, CompactNode<K, V> node1) { return new Value2Index1Node<>(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte npos1, CompactNode<K, V> node1, byte npos2, CompactNode<K, V> node2) { return new Value2Index2Node<>(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1, npos2, node2); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte pos3, K key3, V val3) { return new Value3Index0Node<>(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte pos3, K key3, V val3, byte npos1, CompactNode<K, V> node1) { return new Value3Index1Node<>(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, npos1, node1); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, V val1, byte pos2, K key2, V val2, byte pos3, K key3, V val3, byte pos4, K key4, V val4) { return new Value4Index0Node<>(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4); } static final <K, V> CompactNode<K, V> valNodeOf(AtomicReference<Thread> mutator, int bitmap, int valmap, Object[] nodes, byte payloadArity) { return new MixedIndexNode<>(mutator, bitmap, valmap, nodes, payloadArity); } @SuppressWarnings("unchecked") static final <K, V> CompactNode<K, V> mergeNodes(K key0, int keyHash0, V val0, K key1, int keyHash1, V val1, int shift) { assert key0.equals(key1) == false; if (keyHash0 == keyHash1) { return new HashCollisionNode<>(keyHash0, (K[]) new Object[] { key0, key1 }, (V[]) new Object[] { val0, val1 }); } 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] = val0; // nodes[2] = key1; // nodes[3] = val1; return valNodeOf(null, (byte) mask0, key0, val0, (byte) mask1, key1, val1); } else { // nodes[0] = key1; // nodes[1] = val1; // nodes[2] = key0; // nodes[3] = val0; return valNodeOf(null, (byte) mask1, key1, val1, (byte) mask0, key0, val0); } } else { // values fit on next level final CompactNode<K, V> node = mergeNodes(key0, keyHash0, val0, key1, keyHash1, val1, shift + BIT_PARTITION_SIZE); return valNodeOf(null, (byte) mask0, node); } } static final <K, V> CompactNode<K, V> mergeNodes(CompactNode<K, V> node0, int keyHash0, K key1, int keyHash1, V val1, 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[3]; // store values before node nodes[0] = key1; nodes[1] = val1; nodes[2] = node0; return valNodeOf(null, (byte) mask1, key1, val1, (byte) mask0, node0); } else { // values fit on next level final CompactNode<K, V> node = mergeNodes(node0, keyHash0, key1, keyHash1, val1, shift + BIT_PARTITION_SIZE); return valNodeOf(null, (byte) mask0, node); } } } private static final class MixedIndexNode<K, V> extends CompactNode<K, V> { private AtomicReference<Thread> mutator; private Object[] nodes; final private int bitmap; final private int valmap; final private byte payloadArity; MixedIndexNode(AtomicReference<Thread> mutator, int bitmap, int valmap, Object[] nodes, byte payloadArity) { assert (2 * 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 < 2 * payloadArity; i++) // assert ((nodes[i] instanceof CompactNode) == false); // for (int i = 2 * payloadArity; i < nodes.length; i++) // assert ((nodes[i] instanceof CompactNode) == true); // assert invariant assert nodeInvariant(); } final int bitIndex(int bitpos) { return 2 * payloadArity + Integer.bitCount((bitmap ^ valmap) & (bitpos - 1)); } final int valIndex(int bitpos) { return 2 * Integer.bitCount(valmap & (bitpos - 1)); } @SuppressWarnings("unchecked") @Override boolean containsKey(Object key, int keyHash, int shift) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { return nodes[valIndex(bitpos)].equals(key); } if ((bitmap & bitpos) != 0) { return ((AbstractNode<K, V>) nodes[bitIndex(bitpos)]).containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } return false; } @SuppressWarnings("unchecked") @Override boolean containsKey(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) { return cmp.compare(nodes[valIndex(bitpos)], key) == 0; } if ((bitmap & bitpos) != 0) { return ((AbstractNode<K, V>) nodes[bitIndex(bitpos)]).containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } return false; } @SuppressWarnings("unchecked") @Override Optional<java.util.Map.Entry<K, V>> 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]; final V _val = (V) nodes[valIndex + 1]; final Map.Entry<K, V> entry = entryOf(_key, _val); return Optional.of(entry); } return Optional.empty(); } if ((bitmap & bitpos) != 0) { // node (not value) final AbstractNode<K, V> subNode = ((AbstractNode<K, V>) nodes[bitIndex(bitpos)]); return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } return Optional.empty(); } @SuppressWarnings("unchecked") @Override Optional<java.util.Map.Entry<K, V>> 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]; final V _val = (V) nodes[valIndex + 1]; final Map.Entry<K, V> entry = entryOf(_key, _val); return Optional.of(entry); } return Optional.empty(); } if ((bitmap & bitpos) != 0) { // node (not value) final AbstractNode<K, V> subNode = ((AbstractNode<K, V>) nodes[bitIndex(bitpos)]); return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } return Optional.empty(); } @SuppressWarnings("unchecked") @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V 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)) { final Object currentVal = nodes[valIndex + 1]; if (currentVal.equals(val)) { return Result.unchanged(this); } // update mapping final CompactNode<K, V> thisNew; if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[valIndex + 1] = val; thisNew = this; } else { final Object[] editableNodes = copyAndSet(this.nodes, valIndex + 1, val); thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); } return Result.updated(thisNew, (V) currentVal); } else { final CompactNode<K, V> nodeNew = mergeNodes((K) nodes[valIndex], nodes[valIndex].hashCode(), (V) nodes[valIndex + 1], key, keyHash, val, shift + BIT_PARTITION_SIZE); final int offset = 2 * (payloadArity - 1); final int index = Integer.bitCount(((bitmap | bitpos) ^ (valmap & ~bitpos)) & (bitpos - 1)); final Object[] editableNodes = copyAndMoveToBackPair(this.nodes, valIndex, offset + index, nodeNew); final CompactNode<K, V> thisNew = CompactNode.<K, V> 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 CompactNode<K, V> subNode = (CompactNode<K, V>) nodes[bitIndex]; final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = subNode.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactNode<K, V> thisNew; // modify current node (set replacement node) if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[bitIndex] = subNodeResult.getNode(); thisNew = this; } else { final Object[] editableNodes = copyAndSet(this.nodes, bitIndex, subNodeResult.getNode()); thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); } if (subNodeResult.hasReplacedValue()) { return Result.updated(thisNew, subNodeResult.getReplacedValue()); } return Result.modified(thisNew); } else { // no value final Object[] editableNodes = copyAndInsertPair(this.nodes, valIndex(bitpos), key, val); final CompactNode<K, V> thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap | bitpos, valmap | bitpos, editableNodes, (byte) (payloadArity + 1)); return Result.modified(thisNew); } } @SuppressWarnings("unchecked") @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V 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) { final Object currentVal = nodes[valIndex + 1]; if (cmp.compare(currentVal, val) == 0) { return Result.unchanged(this); } // update mapping final CompactNode<K, V> thisNew; if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[valIndex + 1] = val; thisNew = this; } else { final Object[] editableNodes = copyAndSet(this.nodes, valIndex + 1, val); thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); } return Result.updated(thisNew, (V) currentVal); } else { final CompactNode<K, V> nodeNew = mergeNodes((K) nodes[valIndex], nodes[valIndex].hashCode(), (V) nodes[valIndex + 1], key, keyHash, val, shift + BIT_PARTITION_SIZE); final int offset = 2 * (payloadArity - 1); final int index = Integer.bitCount(((bitmap | bitpos) ^ (valmap & ~bitpos)) & (bitpos - 1)); final Object[] editableNodes = copyAndMoveToBackPair(this.nodes, valIndex, offset + index, nodeNew); final CompactNode<K, V> thisNew = CompactNode.<K, V> 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 CompactNode<K, V> subNode = (CompactNode<K, V>) nodes[bitIndex]; final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = subNode.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactNode<K, V> thisNew; // modify current node (set replacement node) if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[bitIndex] = subNodeResult.getNode(); thisNew = this; } else { final Object[] editableNodes = copyAndSet(this.nodes, bitIndex, subNodeResult.getNode()); thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); } if (subNodeResult.hasReplacedValue()) { return Result.updated(thisNew, subNodeResult.getReplacedValue()); } return Result.modified(thisNew); } else { // no value final Object[] editableNodes = copyAndInsertPair(this.nodes, valIndex(bitpos), key, val); final CompactNode<K, V> thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap | bitpos, valmap | bitpos, editableNodes, (byte) (payloadArity + 1)); return Result.modified(thisNew); } } @SuppressWarnings("unchecked") @Override Result<K, V, ? extends CompactNode<K, V>> 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)) { return Result.unchanged(this); } if (this.arity() == 5) { return Result.modified(removeInplaceValueAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemovePair(this.nodes, valIndex); final CompactNode<K, V> thisNew = CompactNode.<K, V> valNodeOf(mutator, this.bitmap & ~bitpos, this.valmap & ~bitpos, editableNodes, (byte) (payloadArity - 1)); return Result.modified(thisNew); } } else if ((bitmap & bitpos) != 0) { // node (not value) final int bitIndex = bitIndex(bitpos); final CompactNode<K, V> subNode = (CompactNode<K, V>) nodes[bitIndex]; final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = subNode.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactNode<K, V> subNodeNew = subNodeResult.getNode(); switch (subNodeNew.sizePredicate()) { case 0: { // remove node if (this.arity() == 5) { return Result.modified(removeSubNodeAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemovePair(this.nodes, bitIndex); final CompactNode<K, V> thisNew = CompactNode.<K, V> 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 = copyAndMoveToFrontPair(this.nodes, bitIndex, valIndexNew, subNodeNew.headKey(), subNodeNew.headVal()); final CompactNode<K, V> thisNew = CompactNode.<K, V> 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 CompactNode<K, V> thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); return Result.modified(thisNew); } } } } return Result.unchanged(this); } @SuppressWarnings("unchecked") @Override Result<K, V, ? extends CompactNode<K, V>> 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) { return Result.unchanged(this); } if (this.arity() == 5) { return Result.modified(removeInplaceValueAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemovePair(this.nodes, valIndex); final CompactNode<K, V> thisNew = CompactNode.<K, V> valNodeOf(mutator, this.bitmap & ~bitpos, this.valmap & ~bitpos, editableNodes, (byte) (payloadArity - 1)); return Result.modified(thisNew); } } else if ((bitmap & bitpos) != 0) { // node (not value) final int bitIndex = bitIndex(bitpos); final CompactNode<K, V> subNode = (CompactNode<K, V>) nodes[bitIndex]; final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = subNode.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactNode<K, V> subNodeNew = subNodeResult.getNode(); switch (subNodeNew.sizePredicate()) { case 0: { // remove node if (this.arity() == 5) { return Result.modified(removeSubNodeAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemovePair(this.nodes, bitIndex); final CompactNode<K, V> thisNew = CompactNode.<K, V> 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 = copyAndMoveToFrontPair(this.nodes, bitIndex, valIndexNew, subNodeNew.headKey(), subNodeNew.headVal()); final CompactNode<K, V> thisNew = CompactNode.<K, V> 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 CompactNode<K, V> thisNew = CompactNode.<K, V> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); return Result.modified(thisNew); } } } } return Result.unchanged(this); } @SuppressWarnings("unchecked") private CompactNode<K, V> 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 CompactNode<K, V> node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; final CompactNode<K, V> node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; final CompactNode<K, V> node3 = (CompactNode<K, V>) nodes[payloadArity + 2]; final CompactNode<K, V> node4 = (CompactNode<K, V>) 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 V val1; 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 CompactNode<K, V> node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; final CompactNode<K, V> node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; final CompactNode<K, V> node3 = (CompactNode<K, V>) nodes[payloadArity + 2]; if (mask < pos1) { key1 = (K) nodes[2]; val1 = (V) nodes[3]; } else { key1 = (K) nodes[0]; val1 = (V) nodes[1]; } return valNodeOf(mutator, pos1, key1, val1, 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 V val1; final V val2; final int nmap = ((bitmap & ~bitpos) ^ (valmap & ~bitpos)); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final CompactNode<K, V> node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; final CompactNode<K, V> node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; if (mask < pos1) { key1 = (K) nodes[2]; val1 = (V) nodes[3]; key2 = (K) nodes[4]; val2 = (V) nodes[5]; } else if (mask < pos2) { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[4]; val2 = (V) nodes[5]; } else { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[2]; val2 = (V) nodes[3]; } return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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 V val1; final V val2; final V val3; final int nmap = ((bitmap & ~bitpos) ^ (valmap & ~bitpos)); final byte npos1 = recoverMask(nmap, (byte) 1); final CompactNode<K, V> node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; if (mask < pos1) { key1 = (K) nodes[2]; val1 = (V) nodes[3]; key2 = (K) nodes[4]; val2 = (V) nodes[5]; key3 = (K) nodes[6]; val3 = (V) nodes[7]; } else if (mask < pos2) { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[4]; val2 = (V) nodes[5]; key3 = (K) nodes[6]; val3 = (V) nodes[7]; } else if (mask < pos3) { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[2]; val2 = (V) nodes[3]; key3 = (K) nodes[6]; val3 = (V) nodes[7]; } else { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[2]; val2 = (V) nodes[3]; key3 = (K) nodes[4]; val3 = (V) nodes[5]; } return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, 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; final V val1; final V val2; final V val3; final V val4; if (mask < pos1) { key1 = (K) nodes[2]; val1 = (V) nodes[3]; key2 = (K) nodes[4]; val2 = (V) nodes[5]; key3 = (K) nodes[6]; val3 = (V) nodes[7]; key4 = (K) nodes[8]; val4 = (V) nodes[9]; } else if (mask < pos2) { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[4]; val2 = (V) nodes[5]; key3 = (K) nodes[6]; val3 = (V) nodes[7]; key4 = (K) nodes[8]; val4 = (V) nodes[9]; } else if (mask < pos3) { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[2]; val2 = (V) nodes[3]; key3 = (K) nodes[6]; val3 = (V) nodes[7]; key4 = (K) nodes[8]; val4 = (V) nodes[9]; } else if (mask < pos4) { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[2]; val2 = (V) nodes[3]; key3 = (K) nodes[4]; val3 = (V) nodes[5]; key4 = (K) nodes[8]; val4 = (V) nodes[9]; } else { key1 = (K) nodes[0]; val1 = (V) nodes[1]; key2 = (K) nodes[2]; val2 = (V) nodes[3]; key3 = (K) nodes[4]; val3 = (V) nodes[5]; key4 = (K) nodes[6]; val4 = (V) nodes[7]; } return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4); } default: { throw new IllegalStateException(); } } } @SuppressWarnings("unchecked") private CompactNode<K, V> 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[2]; final K key3 = (K) nodes[4]; final K key4 = (K) nodes[6]; final V val1 = (V) nodes[1]; final V val2 = (V) nodes[3]; final V val3 = (V) nodes[5]; final V val4 = (V) nodes[7]; return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4); } 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[2]; final K key3 = (K) nodes[4]; final V val1 = (V) nodes[1]; final V val2 = (V) nodes[3]; final V val3 = (V) nodes[5]; final int nmap = ((bitmap & ~bitpos) ^ valmap); final byte npos1 = recoverMask(nmap, (byte) 1); final CompactNode<K, V> node1; if (mask < npos1) { node1 = (CompactNode<K, V>) nodes[payloadArity + 1]; } else { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; } return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, 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[2]; final V val1 = (V) nodes[1]; final V val2 = (V) nodes[3]; final int nmap = ((bitmap & ~bitpos) ^ valmap); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final CompactNode<K, V> node1; final CompactNode<K, V> node2; if (mask < npos1) { node1 = (CompactNode<K, V>) nodes[payloadArity + 1]; node2 = (CompactNode<K, V>) nodes[payloadArity + 2]; } else if (mask < npos2) { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 2]; } else { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; } return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1, npos2, node2); } case 4: { final int map = valmap; final byte pos1 = recoverMask(map, (byte) 1); final K key1 = (K) nodes[0]; final V val1 = (V) nodes[1]; 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 CompactNode<K, V> node1; final CompactNode<K, V> node2; final CompactNode<K, V> node3; if (mask < npos1) { node1 = (CompactNode<K, V>) nodes[payloadArity + 1]; node2 = (CompactNode<K, V>) nodes[payloadArity + 2]; node3 = (CompactNode<K, V>) nodes[payloadArity + 3]; } else if (mask < npos2) { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 2]; node3 = (CompactNode<K, V>) nodes[payloadArity + 3]; } else if (mask < npos3) { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; node3 = (CompactNode<K, V>) nodes[payloadArity + 3]; } else { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; node3 = (CompactNode<K, V>) nodes[payloadArity + 2]; } return valNodeOf(mutator, pos1, key1, val1, 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 CompactNode<K, V> node1; final CompactNode<K, V> node2; final CompactNode<K, V> node3; final CompactNode<K, V> node4; if (mask < npos1) { node1 = (CompactNode<K, V>) nodes[payloadArity + 1]; node2 = (CompactNode<K, V>) nodes[payloadArity + 2]; node3 = (CompactNode<K, V>) nodes[payloadArity + 3]; node4 = (CompactNode<K, V>) nodes[payloadArity + 4]; } else if (mask < npos2) { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 2]; node3 = (CompactNode<K, V>) nodes[payloadArity + 3]; node4 = (CompactNode<K, V>) nodes[payloadArity + 4]; } else if (mask < npos3) { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; node3 = (CompactNode<K, V>) nodes[payloadArity + 3]; node4 = (CompactNode<K, V>) nodes[payloadArity + 4]; } else if (mask < npos4) { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; node3 = (CompactNode<K, V>) nodes[payloadArity + 2]; node4 = (CompactNode<K, V>) nodes[payloadArity + 4]; } else { node1 = (CompactNode<K, V>) nodes[payloadArity + 0]; node2 = (CompactNode<K, V>) nodes[payloadArity + 1]; node3 = (CompactNode<K, V>) nodes[payloadArity + 2]; node4 = (CompactNode<K, V>) 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[2 * index]; } @SuppressWarnings("unchecked") @Override V getValue(int index) { return (V) nodes[2 * index + 1]; } @SuppressWarnings("unchecked") @Override public AbstractNode<K, V> getNode(int index) { final int offset = 2 * payloadArity; return (AbstractNode<K, V>) nodes[offset + index]; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(nodes, 0, 2 * payloadArity); } @SuppressWarnings("unchecked") @Override Iterator<AbstractNode<K, V>> nodeIterator() { final int offset = 2 * payloadArity; for (int i = offset; i < nodes.length - offset; i++) { assert ((nodes[i] instanceof AbstractNode) == true); } return (Iterator) ArrayIterator.of(nodes, offset, nodes.length - offset); } @SuppressWarnings("unchecked") @Override K headKey() { assert hasPayload(); return (K) nodes[0]; } @SuppressWarnings("unchecked") @Override V headVal() { assert hasPayload(); return (V) nodes[1]; } @Override boolean hasPayload() { return payloadArity != 0; } @Override int payloadArity() { return payloadArity; } @Override boolean hasNodes() { return 2 * payloadArity != nodes.length; } @Override int nodeArity() { return nodes.length - 2 * 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; } MixedIndexNode<?, ?> that = (MixedIndexNode<?, ?>) 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() { final StringBuilder bldr = new StringBuilder(); bldr.append('['); for (byte i = 0; i < payloadArity(); i++) { final byte pos = (byte) recoverMask(valmap, (byte) (i+1)); bldr.append(String.format("@%d: %s=%s", pos, getKey(i), getValue(i))); // bldr.append(String.format("@%d: %s=%s", pos, "key", "val")); if (!((i + 1) == payloadArity())) { bldr.append(", "); } } if (payloadArity() > 0 && nodeArity() > 0) { bldr.append(", "); } for (byte i = 0; i < nodeArity(); i++) { final byte pos = (byte) recoverMask(bitmap ^ valmap, (byte) (i+1)); bldr.append(String.format("@%d: %s", pos, getNode(i))); // bldr.append(String.format("@%d: %s", pos, "node")); if (!((i + 1) == nodeArity())) { bldr.append(", "); } } bldr.append(']'); return bldr.toString(); } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } } // TODO: replace by immutable cons list private static final class HashCollisionNode<K, V> extends CompactNode<K, V> { private final K[] keys; private final V[] vals; private final int hash; HashCollisionNode(int hash, K[] keys, V[] vals) { this.keys = keys; this.vals = vals; this.hash = hash; assert payloadArity() >= 2; } @Override SupplierIterator<K, V> payloadIterator() { // TODO: change representation of keys and values assert keys.length == vals.length; final Object[] keysAndVals = new Object[keys.length + vals.length]; for (int i = 0; i < keys.length; i++) { keysAndVals[2 * i] = keys[i]; keysAndVals[2 * i + 1] = vals[i]; } return ArrayKeyValueIterator.of(keysAndVals); } @Override public String toString() { final Object[] keysAndVals = new Object[keys.length + vals.length]; for (int i = 0; i < keys.length; i++) { keysAndVals[2 * i] = keys[i]; keysAndVals[2 * i + 1] = vals[i]; } return Arrays.toString(keysAndVals); } @Override Iterator<CompactNode<K, V>> nodeIterator() { return Collections.emptyIterator(); } @Override K headKey() { assert hasPayload(); return keys[0]; } @Override V headVal() { assert hasPayload(); return vals[0]; } @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 TrieMap} instance. */ @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { if (this.hash != keyHash) { return Result.modified(mergeNodes(this, this.hash, key, keyHash, val, shift)); } for (int i = 0; i < keys.length; i++) { if (cmp.compare(keys[i], key) == 0) { final V currentVal = vals[i]; if (cmp.compare(currentVal, val) == 0) { return Result.unchanged(this); } final CompactNode<K, V> thisNew; // // update mapping // if (isAllowedToEdit(this.mutator, mutator)) { // // no copying if already editable // this.vals[i] = val; // thisNew = this; // } else { @SuppressWarnings("unchecked") final V[] editableVals = (V[]) copyAndSet(this.vals, i, val); thisNew = new HashCollisionNode<>(this.hash, this.keys, editableVals); return Result.updated(thisNew, currentVal); } } // no value @SuppressWarnings("unchecked") final K[] keysNew = (K[]) copyAndInsert(keys, keys.length, key); @SuppressWarnings("unchecked") final V[] valsNew = (V[]) copyAndInsert(vals, vals.length, val); return Result.modified(new HashCollisionNode<>(keyHash, keysNew, valsNew)); } /** * Removes an object if present. Note, that this implementation always * returns a new immutable {@link TrieMap} instance. */ @SuppressWarnings("unchecked") @Override Result<K, V, ? extends CompactNode<K, V>> 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(CompactNode.<K, V> 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]; final V theOtherVal = (i == 0) ? vals[1] : vals[0]; return CompactNode.<K, V> valNodeOf(mutator).updated(mutator, theOtherKey, keyHash, theOtherVal, 0, cmp); } else { return Result.modified(new HashCollisionNode<>(keyHash, (K[]) copyAndRemove(keys, i), (V[]) copyAndRemove(vals, 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 V getValue(int index) { return vals[index]; } @Override public CompactNode<K, V> 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(); final Object otherVal = it.next(); for (int i = 0; i < keys.length; i++) { final K key = keys[i]; final V val = vals[i]; if (key.equals(otherKey) && val.equals(otherVal)) { continue outerLoop; } } return false; } return true; } @Override Optional<Map.Entry<K, V>> 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) { final V _val = vals[i]; return Optional.of(entryOf(_key, _val)); } } return Optional.empty(); } // TODO: generate instead of delegate @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { return updated(mutator, key, keyHash, val, shift, EqualityUtils.getDefaultEqualityComparator()); } // TODO: generate instead of delegate @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { return removed(mutator, key, keyHash, shift, EqualityUtils.getDefaultEqualityComparator()); } // TODO: generate instead of delegate @Override boolean containsKey(Object key, int keyHash, int shift) { return containsKey(key, keyHash, shift, EqualityUtils.getDefaultEqualityComparator()); } // TODO: generate instead of delegate @Override Optional<java.util.Map.Entry<K, V>> findByKey(Object key, int keyHash, int shift) { return findByKey(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 TrieMap) { TrieMap that = (TrieMap) other; if (this.size() != that.size()) { return false; } return rootNode.equals(that.rootNode); } return super.equals(other); } /* * For analysis purposes only. */ protected AbstractNode<K, V> getRootNode() { return rootNode; } /* * For analysis purposes only. */ protected Iterator<AbstractNode<K, V>> nodeIterator() { return new TrieMapNodeIterator<>(rootNode); } /** * Iterator that first iterates over inlined-values and then continues depth * first recursively. */ private static class TrieMapNodeIterator<K, V> implements Iterator<AbstractNode<K, V>> { final Deque<Iterator<? extends AbstractNode<K, V>>> nodeIteratorStack; TrieMapNodeIterator(AbstractNode<K, V> rootNode) { nodeIteratorStack = new ArrayDeque<>(); nodeIteratorStack.push(Collections.singleton(rootNode).iterator()); } @Override public boolean hasNext() { while (true) { if (nodeIteratorStack.isEmpty()) { return false; } else { if (nodeIteratorStack.peek().hasNext()) { return true; } else { nodeIteratorStack.pop(); continue; } } } } @Override public AbstractNode<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } AbstractNode<K, V> innerNode = nodeIteratorStack.peek().next(); if (innerNode.hasNodes()) { nodeIteratorStack.push(innerNode.nodeIterator()); } return innerNode; } @Override public void remove() { throw new UnsupportedOperationException(); } } private abstract static class AbstractSingletonNode<K, V> extends CompactNode<K, V> { protected abstract byte npos1(); protected final CompactNode<K, V> node1; AbstractSingletonNode(CompactNode<K, V> node1) { this.node1 = node1; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1()) { final CompactNode<K, V> subNode = node1; final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = subNode.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (subNodeResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, subNodeResult.getNode()); if (subNodeResult.hasReplacedValue()) { result = Result.updated(thisNew, subNodeResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1()) { final CompactNode<K, V> subNode = node1; final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = subNode.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (subNodeResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, subNodeResult.getNode()); if (subNodeResult.hasReplacedValue()) { result = Result.updated(thisNew, subNodeResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } private CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { return valNodeOf(mutator, mask, key, val, npos1(), node1); } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1()) { final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (subNodeResult.isModified()) { final CompactNode<K, V> subNodeNew = subNodeResult.getNode(); switch (subNodeNew.sizePredicate()) { case SIZE_EMPTY: case SIZE_ONE: // escalate (singleton or empty) result result = subNodeResult; break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, subNodeNew)); 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == npos1()) { final Result<K, V, ? extends CompactNode<K, V>> subNodeResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (subNodeResult.isModified()) { final CompactNode<K, V> subNodeNew = subNodeResult.getNode(); switch (subNodeNew.sizePredicate()) { case SIZE_EMPTY: case SIZE_ONE: // escalate (singleton or empty) result result = subNodeResult; break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, subNodeNew)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @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 { 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 { return false; } } @Override Optional<java.util.Map.Entry<K, V>> 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 { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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 { return Optional.empty(); } } @Override K getKey(int index) { throw new UnsupportedOperationException(); } @Override V getValue(int index) { throw new UnsupportedOperationException(); } @Override public AbstractNode<K, V> getNode(int index) { if (index == 0) { return node1; } else { throw new IndexOutOfBoundsException(); } } @SuppressWarnings("unchecked") @Override Iterator<AbstractNode<K, V>> nodeIterator() { return ArrayIterator.<AbstractNode<K, V>> of(new AbstractNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, V> 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."); } @Override V headVal() { throw new UnsupportedOperationException("No value in this kind of node."); } } private static final class SingletonNodeAtMask0Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 0; } SingletonNodeAtMask0Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask1Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 1; } SingletonNodeAtMask1Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask2Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 2; } SingletonNodeAtMask2Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask3Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 3; } SingletonNodeAtMask3Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask4Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 4; } SingletonNodeAtMask4Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask5Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 5; } SingletonNodeAtMask5Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask6Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 6; } SingletonNodeAtMask6Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask7Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 7; } SingletonNodeAtMask7Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask8Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 8; } SingletonNodeAtMask8Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask9Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 9; } SingletonNodeAtMask9Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask10Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 10; } SingletonNodeAtMask10Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask11Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 11; } SingletonNodeAtMask11Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask12Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 12; } SingletonNodeAtMask12Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask13Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 13; } SingletonNodeAtMask13Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask14Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 14; } SingletonNodeAtMask14Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask15Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 15; } SingletonNodeAtMask15Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask16Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 16; } SingletonNodeAtMask16Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask17Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 17; } SingletonNodeAtMask17Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask18Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 18; } SingletonNodeAtMask18Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask19Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 19; } SingletonNodeAtMask19Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask20Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 20; } SingletonNodeAtMask20Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask21Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 21; } SingletonNodeAtMask21Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask22Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 22; } SingletonNodeAtMask22Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask23Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 23; } SingletonNodeAtMask23Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask24Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 24; } SingletonNodeAtMask24Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask25Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 25; } SingletonNodeAtMask25Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask26Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 26; } SingletonNodeAtMask26Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask27Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 27; } SingletonNodeAtMask27Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask28Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 28; } SingletonNodeAtMask28Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask29Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 29; } SingletonNodeAtMask29Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask30Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 30; } SingletonNodeAtMask30Node(CompactNode<K, V> node1) { super(node1); } } private static final class SingletonNodeAtMask31Node<K, V> extends AbstractSingletonNode<K, V> { @Override protected byte npos1() { return 31; } SingletonNodeAtMask31Node(CompactNode<K, V> node1) { super(node1); } } private static final class Value0Index0Node<K, V> extends CompactNode<K, V> { Value0Index0Node(final AtomicReference<Thread> mutator) { assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); return Result.modified(valNodeOf(mutator, mask, key, val)); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); return Result.modified(valNodeOf(mutator, mask, key, val)); } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { return Result.unchanged(this); } @Override Result<K, V, ? extends CompactNode<K, V>> 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<java.util.Map.Entry<K, V>> findByKey(Object key, int keyHash, int shift) { return Optional.empty(); } @Override Optional<java.util.Map.Entry<K, V>> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { return Optional.empty(); } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] {}); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] {}); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override V headVal() { throw new UnsupportedOperationException("Node does not directly contain a value."); } @Override AbstractNode<K, V> getNode(int index) { throw new IllegalStateException("Index out of range."); } @Override K getKey(int index) { throw new IllegalStateException("Index out of range."); } @Override V getValue(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 Value0Index2Node<K, V> extends CompactNode<K, V> { private final byte npos1; private final CompactNode<K, V> node1; private final byte npos2; private final CompactNode<K, V> node2; Value0Index2Node(final AtomicReference<Thread> mutator, final byte npos1, final CompactNode<K, V> node1, final byte npos2, final CompactNode<K, V> node2) { this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { return valNodeOf(mutator, mask, key, val, 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 { 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<java.util.Map.Entry<K, V>> 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<java.util.Map.Entry<K, V>> 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<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1, node2 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 2; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] {}); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override V headVal() { throw new UnsupportedOperationException("Node does not directly contain a value."); } @Override AbstractNode<K, V> 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 V getValue(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; } Value0Index2Node<?, ?> that = (Value0Index2Node<?, ?>) 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 Value0Index3Node<K, V> extends CompactNode<K, V> { private final byte npos1; private final CompactNode<K, V> node1; private final byte npos2; private final CompactNode<K, V> node2; private final byte npos3; private final CompactNode<K, V> node3; Value0Index3Node(final AtomicReference<Thread> mutator, final byte npos1, final CompactNode<K, V> node1, final byte npos2, final CompactNode<K, V> node2, final byte npos3, final CompactNode<K, V> node3) { this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; this.npos3 = npos3; this.node3 = node3; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node3.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node3.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node3.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node3.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { return valNodeOf(mutator, mask, key, val, 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 { 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<java.util.Map.Entry<K, V>> 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<java.util.Map.Entry<K, V>> 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<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1, node2, node3 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 3; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] {}); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override V headVal() { throw new UnsupportedOperationException("Node does not directly contain a value."); } @Override AbstractNode<K, V> 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 V getValue(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; } Value0Index3Node<?, ?> that = (Value0Index3Node<?, ?>) 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 Value0Index4Node<K, V> extends CompactNode<K, V> { private final byte npos1; private final CompactNode<K, V> node1; private final byte npos2; private final CompactNode<K, V> node2; private final byte npos3; private final CompactNode<K, V> node3; private final byte npos4; private final CompactNode<K, V> node4; Value0Index4Node(final AtomicReference<Thread> mutator, final byte npos1, final CompactNode<K, V> node1, final byte npos2, final CompactNode<K, V> node2, final byte npos3, final CompactNode<K, V> node3, final byte npos4, final CompactNode<K, V> 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, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3, npos4, node4); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3, npos4, node4); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node3.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode(), npos4, node4); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos4) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node4.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3, npos4, node4); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3, npos4, node4); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node3.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode(), npos4, node4); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos4) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node4.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node3.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node4.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node3.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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, V, ? extends CompactNode<K, V>> nestedResult = node4.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { return valNodeOf(mutator, mask, key, val, npos1, node1, npos2, node2, npos3, node3, npos4, node4); } @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<java.util.Map.Entry<K, V>> 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<java.util.Map.Entry<K, V>> 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<CompactNode<K, V>> nodeIterator() { return ArrayIterator .<CompactNode<K, V>> of(new CompactNode[] { node1, node2, node3, node4 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 4; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] {}); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override V headVal() { throw new UnsupportedOperationException("Node does not directly contain a value."); } @Override AbstractNode<K, V> 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 V getValue(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; } Value0Index4Node<?, ?> that = (Value0Index4Node<?, ?>) 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 Value1Index0Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; Value1Index0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated(valNodeOf(mutator, pos1, key1, val), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated(valNodeOf(mutator, pos1, key1, val), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(CompactNode.<K, V> valNodeOf(mutator)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(CompactNode.<K, V> valNodeOf(mutator)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1); } else { return valNodeOf(mutator, pos1, key1, val1, mask, key, val); } } @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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] {}); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; 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(); result = prime * result + val1.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; } Value1Index0Node<?, ?> that = (Value1Index0Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s=%s]", pos1, key1, val1); } } private static final class Value1Index1Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte npos1; private final CompactNode<K, V> node1; Value1Index1Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte npos1, final CompactNode<K, V> node1) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.npos1 = npos1; this.node1 = node1; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated(valNodeOf(mutator, pos1, key1, val, npos1, node1), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, 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, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated(valNodeOf(mutator, pos1, key1, val, npos1, node1), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, 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, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, 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 { 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; 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 + val1.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; } Value1Index1Node<?, ?> that = (Value1Index1Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { 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=%s, @%d: %s]", pos1, key1, val1, npos1, node1); } } private static final class Value1Index2Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte npos1; private final CompactNode<K, V> node1; private final byte npos2; private final CompactNode<K, V> node2; Value1Index2Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte npos1, final CompactNode<K, V> node1, final byte npos2, final CompactNode<K, V> node2) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, npos1, node1, npos2, node2), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, 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, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, mask, nestedResult.getNode(), npos2, node2); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, npos1, node1, npos2, node2), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, 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, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, mask, nestedResult.getNode(), npos2, node2); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, npos1, node1, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, 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 { 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } 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<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1, node2 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 2; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; 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 + val1.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; } Value1Index2Node<?, ?> that = (Value1Index2Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { 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=%s, @%d: %s, @%d: %s]", pos1, key1, val1, npos1, node1, npos2, node2); } } private static final class Value1Index3Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte npos1; private final CompactNode<K, V> node1; private final byte npos2; private final CompactNode<K, V> node2; private final byte npos3; private final CompactNode<K, V> node3; Value1Index3Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte npos1, final CompactNode<K, V> node1, final byte npos2, final CompactNode<K, V> node2, final byte npos3, final CompactNode<K, V> node3) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; this.npos3 = npos3; this.node3 = node3; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, npos1, node1, npos2, node2, npos3, node3), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, 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, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, mask, nestedResult.getNode(), npos2, node2, npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, nestedResult.getNode(), npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node3.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, npos1, node1, npos2, node2, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, npos1, node1, npos2, node2, npos3, node3), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, 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, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, mask, nestedResult.getNode(), npos2, node2, npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, nestedResult.getNode(), npos3, node3); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node3.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, npos1, node1, npos2, node2, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> nestedResult = node3.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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, V, ? extends CompactNode<K, V>> nestedResult = node3.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, npos1, node1, npos2, node2, npos3, node3); } else { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, 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 == 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } 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<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1, node2, node3 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 3; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; 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 + val1.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; } Value1Index3Node<?, ?> that = (Value1Index3Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { 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=%s, @%d: %s, @%d: %s, @%d: %s]", pos1, key1, val1, npos1, node1, npos2, node2, npos3, node3); } } private static final class Value2Index0Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte pos2; private final K key2; private final V val2; Value2Index0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte pos2, final K key2, final V val2) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.pos2 = pos2; this.key2 = key2; this.val2 = val2; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated(valNodeOf(mutator, pos1, key1, val, pos2, key2, val2), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, val2, mask, node)); } } else if (mask == pos2) { if (key.equals(key2)) { if (val.equals(val2)) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated(valNodeOf(mutator, pos1, key1, val, pos2, key2, val2), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, val2, mask, node)); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { if (cmp.compare(val, val2) == 0) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2)); } 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, val1)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, pos2, key2, val2); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, pos2, key2, val2); } else { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, key, val); } } @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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(entryOf(key2, val2)); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(entryOf(key2, val2)); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] {}); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1, key2, val2 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 2; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; case 1: return val2; 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 + val1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + val2.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; } Value2Index0Node<?, ?> that = (Value2Index0Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (!val2.equals(that.val2)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s=%s, @%d: %s=%s]", pos1, key1, val1, pos2, key2, val2); } } private static final class Value2Index1Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte pos2; private final K key2; private final V val2; private final byte npos1; private final CompactNode<K, V> node1; Value2Index1Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte pos2, final K key2, final V val2, final byte npos1, final CompactNode<K, V> node1) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.pos2 = pos2; this.key2 = key2; this.val2 = val2; this.npos1 = npos1; this.node1 = node1; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, npos1, node1), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (key.equals(key2)) { if (val.equals(val2)) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, npos1, node1), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, npos1, node1), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { if (cmp.compare(val, val2) == 0) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, npos1, node1), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, 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, val1, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, 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, val1, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, pos2, key2, val2, npos1, node1); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, pos2, key2, val2, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, key, val, 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 { 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(entryOf(key2, val2)); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(entryOf(key2, val2)); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1, key2, val2 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 2; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; case 1: return val2; 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 + val1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + val2.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; } Value2Index1Node<?, ?> that = (Value2Index1Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (!val2.equals(that.val2)) { 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=%s, @%d: %s=%s, @%d: %s]", pos1, key1, val1, pos2, key2, val2, npos1, node1); } } private static final class Value2Index2Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte pos2; private final K key2; private final V val2; private final byte npos1; private final CompactNode<K, V> node1; private final byte npos2; private final CompactNode<K, V> node2; Value2Index2Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte pos2, final K key2, final V val2, final byte npos1, final CompactNode<K, V> node1, final byte npos2, final CompactNode<K, V> node2) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.pos2 = pos2; this.key2 = key2; this.val2 = val2; this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, npos1, node1, npos2, node2), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == pos2) { if (key.equals(key2)) { if (val.equals(val2)) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, npos1, node1, npos2, node2), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, nestedResult.getNode(), npos2, node2); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, npos1, node1, npos2, node2), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { if (cmp.compare(val, val2) == 0) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, npos1, node1, npos2, node2), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, nestedResult.getNode(), npos2, node2); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node2.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, 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, val1, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, 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, val1, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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, V, ? extends CompactNode<K, V>> nestedResult = node2.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, pos2, key2, val2, npos1, node1, npos2, node2); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, pos2, key2, val2, npos1, node1, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, key, val, 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 == 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(entryOf(key2, val2)); } 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(entryOf(key2, val2)); } 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<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1, node2 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 2; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1, key2, val2 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 2; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; case 1: return val2; 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 + val1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + val2.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; } Value2Index2Node<?, ?> that = (Value2Index2Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (!val2.equals(that.val2)) { 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=%s, @%d: %s=%s, @%d: %s, @%d: %s]", pos1, key1, val1, pos2, key2, val2, npos1, node1, npos2, node2); } } private static final class Value3Index0Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte pos2; private final K key2; private final V val2; private final byte pos3; private final K key3; private final V val3; Value3Index0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte pos2, final K key2, final V val2, final byte pos3, final K key3, final V val3) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.pos2 = pos2; this.key2 = key2; this.val2 = val2; this.pos3 = pos3; this.key3 = key3; this.val3 = val3; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, pos3, key3, val3), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, mask, node)); } } else if (mask == pos2) { if (key.equals(key2)) { if (val.equals(val2)) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, pos3, key3, val3), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, mask, node)); } } else if (mask == pos3) { if (key.equals(key3)) { if (val.equals(val3)) { result = Result.unchanged(this); } else { // update key3, val3 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val), val3); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key3, key3.hashCode(), val3, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, pos3, key3, val3), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, mask, node)); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { if (cmp.compare(val, val2) == 0) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, pos3, key3, val3), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, mask, node)); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { if (cmp.compare(val, val3) == 0) { result = Result.unchanged(this); } else { // update key3, val3 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val), val3); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key3, key3.hashCode(), val3, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (key.equals(key3)) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3)); } 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, val1, pos3, key3, val3)); } 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, val1, pos2, key2, val2)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, pos2, key2, val2, pos3, key3, val3); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, key, val, pos3, key3, val3); } else { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, key, val); } } @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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(entryOf(key2, val2)); } else if (mask == pos3 && key.equals(key3)) { return Optional.of(entryOf(key3, val3)); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(entryOf(key2, val2)); } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return Optional.of(entryOf(key3, val3)); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] {}); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1, key2, val2, key3, val3 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 3; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; case 1: return val2; case 2: return val3; 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 + val1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + val2.hashCode(); result = prime * result + pos3; result = prime * result + key3.hashCode(); result = prime * result + val3.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; } Value3Index0Node<?, ?> that = (Value3Index0Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (!val2.equals(that.val2)) { return false; } if (pos3 != that.pos3) { return false; } if (!key3.equals(that.key3)) { return false; } if (!val3.equals(that.val3)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s=%s, @%d: %s=%s, @%d: %s=%s]", pos1, key1, val1, pos2, key2, val2, pos3, key3, val3); } } private static final class Value3Index1Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte pos2; private final K key2; private final V val2; private final byte pos3; private final K key3; private final V val3; private final byte npos1; private final CompactNode<K, V> node1; Value3Index1Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte pos2, final K key2, final V val2, final byte pos3, final K key3, final V val3, final byte npos1, final CompactNode<K, V> node1) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.pos2 = pos2; this.key2 = key2; this.val2 = val2; this.pos3 = pos3; this.key3 = key3; this.val3 = val3; this.npos1 = npos1; this.node1 = node1; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, pos3, key3, val3, npos1, node1), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (key.equals(key2)) { if (val.equals(val2)) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, pos3, key3, val3, npos1, node1), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, npos1, node1, mask, node)); } } } else if (mask == pos3) { if (key.equals(key3)) { if (val.equals(val3)) { result = Result.unchanged(this); } else { // update key3, val3 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val, npos1, node1), val3); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key3, key3.hashCode(), val3, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, pos3, key3, val3, npos1, node1), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { if (cmp.compare(val, val2) == 0) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, pos3, key3, val3, npos1, node1), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, npos1, node1, mask, node)); } } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { if (cmp.compare(val, val3) == 0) { result = Result.unchanged(this); } else { // update key3, val3 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val, npos1, node1), val3); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key3, key3.hashCode(), val3, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.updated(mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> thisNew = valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, nestedResult.getNode()); if (nestedResult.hasReplacedValue()) { result = Result.updated(thisNew, nestedResult.getReplacedValue()); } else { result = Result.modified(thisNew); } } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, 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, val1, pos3, key3, val3, 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, val1, pos2, key2, val2, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, 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, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, 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, val1, pos3, key3, val3, 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, val1, pos2, key2, val2, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, V, ? extends CompactNode<K, V>> nestedResult = node1.removed(mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactNode<K, V> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(inlineValue(mutator, mask, updatedNode.headKey(), updatedNode.headVal())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, 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 CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, npos1, node1); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, pos2, key2, val2, pos3, key3, val3, npos1, node1); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, key, val, pos3, key3, val3, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, key, val, 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 == 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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(entryOf(key2, val2)); } else if (mask == pos3 && key.equals(key3)) { return Optional.of(entryOf(key3, val3)); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(entryOf(key2, val2)); } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return Optional.of(entryOf(key3, val3)); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1, key2, val2, key3, val3 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 3; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; case 1: return val2; case 2: return val3; 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 + val1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + val2.hashCode(); result = prime * result + pos3; result = prime * result + key3.hashCode(); result = prime * result + val3.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; } Value3Index1Node<?, ?> that = (Value3Index1Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (!val2.equals(that.val2)) { return false; } if (pos3 != that.pos3) { return false; } if (!key3.equals(that.key3)) { return false; } if (!val3.equals(that.val3)) { 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=%s, @%d: %s=%s, @%d: %s=%s, @%d: %s]", pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, npos1, node1); } } private static final class Value4Index0Node<K, V> extends CompactNode<K, V> { private final byte pos1; private final K key1; private final V val1; private final byte pos2; private final K key2; private final V val2; private final byte pos3; private final K key3; private final V val3; private final byte pos4; private final K key4; private final V val4; Value4Index0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final V val1, final byte pos2, final K key2, final V val2, final byte pos3, final K key3, final V val3, final byte pos4, final K key4, final V val4) { this.pos1 = pos1; this.key1 = key1; this.val1 = val1; this.pos2 = pos2; this.key2 = key2; this.val2 = val2; this.pos3 = pos3; this.key3 = key3; this.val3 = val3; this.pos4 = pos4; this.key4 = key4; this.val4 = val4; assert nodeInvariant(); } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { if (val.equals(val1)) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4, mask, node)); } } else if (mask == pos2) { if (key.equals(key2)) { if (val.equals(val2)) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, pos3, key3, val3, pos4, key4, val4), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, pos4, key4, val4, mask, node)); } } else if (mask == pos3) { if (key.equals(key3)) { if (val.equals(val3)) { result = Result.unchanged(this); } else { // update key3, val3 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val, pos4, key4, val4), val3); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key3, key3.hashCode(), val3, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos4, key4, val4, mask, node)); } } else if (mask == pos4) { if (key.equals(key4)) { if (val.equals(val4)) { result = Result.unchanged(this); } else { // update key4, val4 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val), val4); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key4, key4.hashCode(), val4, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> updated(AtomicReference<Thread> mutator, K key, int keyHash, V val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { if (cmp.compare(val, val1) == 0) { result = Result.unchanged(this); } else { // update key1, val1 result = Result.updated( valNodeOf(mutator, pos1, key1, val, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4), val1); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key1, key1.hashCode(), val1, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4, mask, node)); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { if (cmp.compare(val, val2) == 0) { result = Result.unchanged(this); } else { // update key2, val2 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val, pos3, key3, val3, pos4, key4, val4), val2); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key2, key2.hashCode(), val2, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, pos4, key4, val4, mask, node)); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { if (cmp.compare(val, val3) == 0) { result = Result.unchanged(this); } else { // update key3, val3 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val, pos4, key4, val4), val3); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key3, key3.hashCode(), val3, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos4, key4, val4, mask, node)); } } else if (mask == pos4) { if (cmp.compare(key, key4) == 0) { if (cmp.compare(val, val4) == 0) { result = Result.unchanged(this); } else { // update key4, val4 result = Result.updated( valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val), val4); } } else { // merge into node final CompactNode<K, V> node = mergeNodes(key4, key4.hashCode(), val4, key, keyHash, val, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key, val)); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos3, key3, val3, pos4, key4, val4)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (key.equals(key3)) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos4, key4, val4)); } else { result = Result.unchanged(this); } } else if (mask == pos4) { if (key.equals(key4)) { // remove key4, val4 result = Result.modified(valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, V, ? extends CompactNode<K, V>> 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, V, ? extends CompactNode<K, V>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4)); } 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, val1, pos3, key3, val3, pos4, key4, val4)); } 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, val1, pos2, key2, val2, pos4, key4, val4)); } 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, val1, pos2, key2, val2, pos3, key3, val3)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactNode<K, V> inlineValue(AtomicReference<Thread> mutator, byte mask, K key, V val) { if (mask < pos1) { return valNodeOf(mutator, mask, key, val, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, val1, mask, key, val, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, mask, key, val, pos3, key3, val3, pos4, key4, val4); } else if (mask < pos4) { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, mask, key, val, pos4, key4, val4); } else { return valNodeOf(mutator, pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4, mask, key, val); } } @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<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(entryOf(key2, val2)); } else if (mask == pos3 && key.equals(key3)) { return Optional.of(entryOf(key3, val3)); } else if (mask == pos4 && key.equals(key4)) { return Optional.of(entryOf(key4, val4)); } else { return Optional.empty(); } } @Override Optional<java.util.Map.Entry<K, V>> 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(entryOf(key1, val1)); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(entryOf(key2, val2)); } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return Optional.of(entryOf(key3, val3)); } else if (mask == pos4 && cmp.compare(key, key4) == 0) { return Optional.of(entryOf(key4, val4)); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactNode<K, V>> nodeIterator() { return ArrayIterator.<CompactNode<K, V>> of(new CompactNode[] {}); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, V> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, val1, key2, val2, key3, val3, key4, val4 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 4; } @Override K headKey() { return key1; } @Override V headVal() { return val1; } @Override AbstractNode<K, V> 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 V getValue(int index) { switch (index) { case 0: return val1; case 1: return val2; case 2: return val3; case 3: return val4; 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 + val1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + val2.hashCode(); result = prime * result + pos3; result = prime * result + key3.hashCode(); result = prime * result + val3.hashCode(); result = prime * result + pos4; result = prime * result + key4.hashCode(); result = prime * result + val4.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; } Value4Index0Node<?, ?> that = (Value4Index0Node<?, ?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (!val1.equals(that.val1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (!val2.equals(that.val2)) { return false; } if (pos3 != that.pos3) { return false; } if (!key3.equals(that.key3)) { return false; } if (!val3.equals(that.val3)) { return false; } if (pos4 != that.pos4) { return false; } if (!key4.equals(that.key4)) { return false; } if (!val4.equals(that.val4)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s=%s, @%d: %s=%s, @%d: %s=%s, @%d: %s=%s]", pos1, key1, val1, pos2, key2, val2, pos3, key3, val3, pos4, key4, val4); } } }
package edu.mit.streamjit.impl.compiler2; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.Blob; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.blob.DrainData; import edu.mit.streamjit.impl.common.Configuration; import edu.mit.streamjit.impl.interp.Interpreter; import edu.mit.streamjit.util.CollectionUtils; import edu.mit.streamjit.util.Combinators; import static edu.mit.streamjit.util.LookupUtils.findConstructor; import static edu.mit.streamjit.util.LookupUtils.findVirtual; import edu.mit.streamjit.util.MethodHandlePhaser; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.SwitchPoint; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Phaser; import java.util.concurrent.atomic.AtomicBoolean; /** * The actual blob produced by a Compiler2. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 11/1/2013 */ public class Compiler2BlobHost implements Blob { private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); private static final MethodHandle MAIN_LOOP = findVirtual(LOOKUP, Compiler2BlobHost.class, "mainLoop", void.class, MethodHandle.class); private static final MethodHandle DO_INIT = findVirtual(LOOKUP, Compiler2BlobHost.class, "doInit", void.class); private static final MethodHandle DO_ADJUST = findVirtual(LOOKUP, Compiler2BlobHost.class, "doAdjust", void.class); private static final MethodHandle THROW_NEW_ASSERTION_ERROR = MethodHandles.filterReturnValue( findConstructor(LOOKUP, AssertionError.class, Object.class), MethodHandles.throwException(void.class, AssertionError.class)); private static final MethodHandle NOP = Combinators.nop(); private static final MethodHandle MAIN_LOOP_NOP = MethodHandles.insertArguments(MAIN_LOOP, 1, NOP); /* provided by Compiler2 */ private final ImmutableSet<Worker<?, ?>> workers; private final Configuration config; private final ImmutableSortedSet<Token> inputTokens, outputTokens; private final MethodHandle initCode; private final ImmutableList<MethodHandle> steadyStateCode; private final ImmutableList<MethodHandle> storageAdjusts; /** * Instructions to load items for the init schedule. unload() will * unload all items, as the init schedule only runs if all reads can * be satisfied. */ public ImmutableList<ReadInstruction> initReadInstructions; /** * Instructions to write output from the init schedule. */ public ImmutableList<WriteInstruction> initWriteInstructions; /** * Instructions to move items from init storage to steady-state storage. */ public ImmutableList<Runnable> migrationInstructions; /** * Instructions to load items for the steady-state schedule. unload() * will only unload items loaded by load(); the drain instructions will * retrieve any unconsumed items in the storage. */ public final ImmutableList<ReadInstruction> readInstructions; /** * Instructions to write output from the steady-state schedule. */ public final ImmutableList<WriteInstruction> writeInstructions; /** * Instructions to extract items from steady-state storage for transfer * to a DrainData object. For input storage, this only extracts * unconsumed items (items at live indices except the last throughput * indices, which are covered by the read instructions' unload()). */ public final ImmutableList<DrainInstruction> drainInstructions; /* provided by the host */ private final boolean collectTimings; private final ImmutableMap<Token, Integer> minimumBufferCapacity; private ImmutableMap<Token, Buffer> buffers; private final ImmutableList<Runnable> coreCode; private final SwitchPoint sp1 = new SwitchPoint(), sp2 = new SwitchPoint(); private final Phaser barrier; private volatile Runnable drainCallback; private volatile DrainData drainData; public Compiler2BlobHost(ImmutableSet<Worker<?, ?>> workers, Configuration configuration, ImmutableSortedSet<Token> inputTokens, ImmutableSortedSet<Token> outputTokens, MethodHandle initCode, ImmutableList<MethodHandle> steadyStateCode, ImmutableList<MethodHandle> storageAdjusts, List<ReadInstruction> initReadInstructions, List<WriteInstruction> initWriteInstructions, List<Runnable> migrationInstructions, List<ReadInstruction> readInstructions, List<WriteInstruction> writeInstructions, List<DrainInstruction> drainInstructions) { this.workers = workers; this.config = configuration; this.inputTokens = inputTokens; this.outputTokens = outputTokens; this.initCode = initCode; this.steadyStateCode = steadyStateCode; this.storageAdjusts = storageAdjusts; this.initReadInstructions = ImmutableList.copyOf(initReadInstructions); this.initWriteInstructions = ImmutableList.copyOf(initWriteInstructions); this.migrationInstructions = ImmutableList.copyOf(migrationInstructions); this.readInstructions = ImmutableList.copyOf(readInstructions); this.writeInstructions = ImmutableList.copyOf(writeInstructions); this.drainInstructions = ImmutableList.copyOf(drainInstructions); this.collectTimings = config.getExtraData("timings") != null ? (Boolean)config.getExtraData("timings") : false; List<Map<Token, Integer>> capacityRequirements = new ArrayList<>(); for (ReadInstruction i : Iterables.concat(this.initReadInstructions, this.readInstructions)) capacityRequirements.add(i.getMinimumBufferCapacity()); for (WriteInstruction i : Iterables.concat(this.initWriteInstructions, this.writeInstructions)) capacityRequirements.add(i.getMinimumBufferCapacity()); this.minimumBufferCapacity = CollectionUtils.union(new Maps.EntryTransformer<Token, List<Integer>, Integer>() { @Override public Integer transformEntry(Token key, List<Integer> value) { return Collections.max(value); } }, capacityRequirements); MethodHandle mainLoop = MAIN_LOOP.bindTo(this), doInit = DO_INIT.bindTo(this), doAdjust = DO_ADJUST.bindTo(this), mainLoopNop = MAIN_LOOP_NOP.bindTo(this); ImmutableList.Builder<MethodHandle> coreCodeHandles = ImmutableList.builder(); for (MethodHandle ssc : this.steadyStateCode) { MethodHandle code = sp1.guardWithTest(mainLoopNop, sp2.guardWithTest(mainLoop.bindTo(ssc), NOP)); coreCodeHandles.add(code); } this.coreCode = Bytecodifier.runnableProxies(coreCodeHandles.build()); MethodHandle throwAE = THROW_NEW_ASSERTION_ERROR.bindTo("Can't happen! Barrier action reached after draining?"); this.barrier = new MethodHandlePhaser(sp1.guardWithTest(doInit, sp2.guardWithTest(doAdjust, throwAE)), coreCode.size()); } @Override public Set<Worker<?, ?>> getWorkers() { return workers; } @Override public Set<Token> getInputs() { return inputTokens; } @Override public Set<Token> getOutputs() { return outputTokens; } @Override public int getMinimumBufferCapacity(Token token) { if (!inputTokens.contains(token) && !outputTokens.contains(token)) throw new IllegalArgumentException(token.toString()+" not an input or output of this blob"); return minimumBufferCapacity.get(token); } @Override public void installBuffers(Map<Token, Buffer> buffers) { if (this.buffers != null) throw new IllegalStateException("installBuffers called more than once"); ImmutableMap.Builder<Token, Buffer> builder = ImmutableMap.builder(); for (Token t : Sets.union(inputTokens, outputTokens)) { Buffer b = buffers.get(t); if (b == null) throw new IllegalArgumentException("no buffer for token "+t); if (b.capacity() < getMinimumBufferCapacity(t)) throw new IllegalArgumentException(String.format( "buffer for %s has capacity %d, but minimum is %d", t, b.capacity(), getMinimumBufferCapacity(t))); builder.put(t, b); } this.buffers = builder.build(); for (ReadInstruction i : Iterables.concat(this.initReadInstructions, this.readInstructions)) i.init(this.buffers); for (WriteInstruction i : Iterables.concat(this.initWriteInstructions, this.writeInstructions)) i.init(this.buffers); } @Override public int getCoreCount() { return coreCode.size(); } @Override public Runnable getCoreCode(int core) { return coreCode.get(core); } @Override public void drain(Runnable callback) { drainCallback = callback; } @Override public DrainData getDrainData() { return drainData; } private void mainLoop(MethodHandle coreCode) throws Throwable { try { coreCode.invokeExact(); } catch (Throwable ex) { barrier.forceTermination(); throw ex; } barrier.arriveAndAwaitAdvance(); } private void doInit() throws Throwable { Stopwatch initTime = null; if (collectTimings) initTime = Stopwatch.createStarted(); for (int i = 0; i < initReadInstructions.size(); ++i) { ReadInstruction inst = initReadInstructions.get(i); while (!inst.load()) if (isDraining()) { doDrain(initReadInstructions.subList(0, i), ImmutableList.<DrainInstruction>of()); return; } } try { initCode.invoke(); } catch (Throwable ex) { barrier.forceTermination(); throw ex; } for (WriteInstruction inst : initWriteInstructions) inst.run(); for (Runnable r : migrationInstructions) r.run(); //Show the GC we won't use these anymore. initReadInstructions = null; initWriteInstructions = null; migrationInstructions = null; readOrDrain(); SwitchPoint.invalidateAll(new SwitchPoint[]{sp1}); if (collectTimings) System.out.println("init time: "+initTime.stop()); } private final Stopwatch adjustTime = Stopwatch.createUnstarted(); private int adjustCount; private void doAdjust() throws Throwable { if (collectTimings) { adjustTime.start(); ++adjustCount; } for (WriteInstruction inst : writeInstructions) { inst.run(); } for (MethodHandle h : storageAdjusts) h.invokeExact(); readOrDrain(); if (collectTimings) adjustTime.stop(); } private void readOrDrain() { for (int i = 0; i < readInstructions.size(); ++i) { ReadInstruction inst = readInstructions.get(i); while (!inst.load()) if (isDraining()) { doDrain(readInstructions.subList(0, i), drainInstructions); return; } } } /** * Extracts elements from storage and puts them in a DrainData for an * interpreter blob. * @param reads read instructions whose load() completed (thus requiring * unload()) * @param drains drain instructions, if we're in the steady-state, or an * empty list if we didn't complete init */ private void doDrain(List<ReadInstruction> reads, List<DrainInstruction> drains) { Stopwatch drainTime = null; if (collectTimings) drainTime = Stopwatch.createStarted(); List<Map<Token, Object[]>> data = new ArrayList<>(reads.size() + drains.size()); for (ReadInstruction i : reads) data.add(i.unload()); for (DrainInstruction i : drains) data.add(i.call()); ImmutableMap<Token, List<Object>> mergedData = CollectionUtils.union(new Maps.EntryTransformer<Token, List<Object[]>, List<Object>>() { @Override public List<Object> transformEntry(Token key, List<Object[]> value) { ImmutableList.Builder<Object> builder = ImmutableList.builder(); for (Object[] v : value) builder.addAll(Arrays.asList(v)); return builder.build(); } }, data); //We have to write our output; the interpreter won't do it for us. Predicate<Token> isOutput = Predicates.in(getOutputs()); for (Map.Entry<Token, List<Object>> e : Maps.filterKeys(mergedData, isOutput).entrySet()) { Buffer b = buffers.get(e.getKey()); Object[] d = e.getValue().toArray(); for (int written = 0; written < d.length;) written += b.write(d, written, d.length-written); } DrainData forInterp = new DrainData(Maps.filterKeys(mergedData, Predicates.not(isOutput)), ImmutableTable.<Integer, String, Object>of()); Interpreter.InterpreterBlobFactory interpFactory = new Interpreter.InterpreterBlobFactory(); Blob interp = interpFactory.makeBlob(workers, interpFactory.getDefaultConfiguration(workers), 1, forInterp); interp.installBuffers(buffers); Runnable interpCode = interp.getCoreCode(0); final AtomicBoolean interpFinished = new AtomicBoolean(); interp.drain(new Runnable() { @Override public void run() { interpFinished.set(true); } }); while (!interpFinished.get()) interpCode.run(); this.drainData = interp.getDrainData(); SwitchPoint.invalidateAll(new SwitchPoint[]{sp1, sp2}); drainCallback.run(); if (collectTimings) { drainTime.stop(); System.out.println("total adjust time: "+adjustTime+" over "+adjustCount+" adjusts"); System.out.println("drain time: "+drainTime); } } private boolean isDraining() { return drainCallback != null; } public static interface ReadInstruction { public void init(Map<Token, Buffer> buffers); public Map<Token, Integer> getMinimumBufferCapacity(); /** * Loads data items from a Buffer into ConcreteStorage. Returns true * if the load was successful. This operation is atomic; either all the * data items are loaded (and load() returns true), or none are and it * returns false. * @return true iff the load succeeded. */ public boolean load(); /** * Retrieves data items from a ConcreteStorage. To be called only after * load() returns true, before executing a steady-state iteration. This * method only retrieves items loaded by load(); a drain instruction * will retrieve other data. * @return */ public Map<Token, Object[]> unload(); } public static interface WriteInstruction extends Runnable { public void init(Map<Token, Buffer> buffers); public Map<Token, Integer> getMinimumBufferCapacity(); } public static interface DrainInstruction extends Callable<Map<Token, Object[]>> { @Override public Map<Token, Object[]> call(); } }
package com.rilixtech; import android.content.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class CountryUtils { private static List<Country> countries; private static Map<String, List<String>> timeZoneAndCountryISOs; /** * Returns image res based on country name code * @param country selected country * @return drawable resource id of country flag. */ public static int getFlagDrawableResId(Country country) { switch (country.getIso()) { case "af": //afghanistan return R.drawable.flag_afghanistan; case "al": //albania return R.drawable.flag_albania; case "dz": //algeria return R.drawable.flag_algeria; case "ad": //andorra return R.drawable.flag_andorra; case "ao": //angola return R.drawable.flag_angola; case "aq": //antarctica // custom return R.drawable.flag_antarctica; case "ar": //argentina return R.drawable.flag_argentina; case "am": //armenia return R.drawable.flag_armenia; case "aw": //aruba return R.drawable.flag_aruba; case "au": //australia return R.drawable.flag_australia; case "at": //austria return R.drawable.flag_austria; case "az": //azerbaijan return R.drawable.flag_azerbaijan; case "bh": //bahrain return R.drawable.flag_bahrain; case "bd": //bangladesh return R.drawable.flag_bangladesh; case "by": //belarus return R.drawable.flag_belarus; case "be": //belgium return R.drawable.flag_belgium; case "bz": //belize return R.drawable.flag_belize; case "bj": //benin return R.drawable.flag_benin; case "bt": //bhutan return R.drawable.flag_bhutan; case "bo": //bolivia, plurinational state of return R.drawable.flag_bolivia; case "ba": //bosnia and herzegovina return R.drawable.flag_bosnia; case "bw": //botswana return R.drawable.flag_botswana; case "br": //brazil return R.drawable.flag_brazil; case "bn": //brunei darussalam // custom return R.drawable.flag_brunei; case "bg": //bulgaria return R.drawable.flag_bulgaria; case "bf": //burkina faso return R.drawable.flag_burkina_faso; case "mm": //myanmar return R.drawable.flag_myanmar; case "bi": //burundi return R.drawable.flag_burundi; case "kh": //cambodia return R.drawable.flag_cambodia; case "cm": //cameroon return R.drawable.flag_cameroon; case "ca": //canada return R.drawable.flag_canada; case "cv": //cape verde return R.drawable.flag_cape_verde; case "cf": //central african republic return R.drawable.flag_central_african_republic; case "td": //chad return R.drawable.flag_chad; case "cl": //chile return R.drawable.flag_chile; case "cn": //china return R.drawable.flag_china; case "cx": //christmas island return R.drawable.flag_christmas_island; case "cc": //cocos (keeling) islands return R.drawable.flag_cocos;// custom case "co": //colombia return R.drawable.flag_colombia; case "km": //comoros return R.drawable.flag_comoros; case "cg": //congo return R.drawable.flag_republic_of_the_congo; case "cd": //congo, the democratic republic of the return R.drawable.flag_democratic_republic_of_the_congo; case "ck": //cook islands return R.drawable.flag_cook_islands; case "cr": //costa rica return R.drawable.flag_costa_rica; case "hr": //croatia return R.drawable.flag_croatia; case "cu": //cuba return R.drawable.flag_cuba; case "cy": //cyprus return R.drawable.flag_cyprus; case "cz": //czech republic return R.drawable.flag_czech_republic; case "dk": //denmark return R.drawable.flag_denmark; case "dj": //djibouti return R.drawable.flag_djibouti; case "tl": //timor-leste return R.drawable.flag_timor_leste; case "ec": //ecuador return R.drawable.flag_ecuador; case "eg": //egypt return R.drawable.flag_egypt; case "sv": //el salvador return R.drawable.flag_el_salvador; case "gq": //equatorial guinea return R.drawable.flag_equatorial_guinea; case "er": //eritrea return R.drawable.flag_eritrea; case "ee": //estonia return R.drawable.flag_estonia; case "et": //ethiopia return R.drawable.flag_ethiopia; case "fk": //falkland islands (malvinas) return R.drawable.flag_falkland_islands; case "fo": //faroe islands return R.drawable.flag_faroe_islands; case "fj": //fiji return R.drawable.flag_fiji; case "fi": //finland return R.drawable.flag_finland; case "fr": //france return R.drawable.flag_france; case "pf": //french polynesia return R.drawable.flag_french_polynesia; case "ga": //gabon return R.drawable.flag_gabon; case "gm": //gambia return R.drawable.flag_gambia; case "ge": //georgia return R.drawable.flag_georgia; case "de": //germany return R.drawable.flag_germany; case "gh": //ghana return R.drawable.flag_ghana; case "gi": //gibraltar return R.drawable.flag_gibraltar; case "gr": //greece return R.drawable.flag_greece; case "gl": //greenland return R.drawable.flag_greenland; case "gt": //guatemala return R.drawable.flag_guatemala; case "gn": //guinea return R.drawable.flag_guinea; case "gw": //guinea-bissau return R.drawable.flag_guinea_bissau; case "gy": //guyana return R.drawable.flag_guyana; case "gf": //guyane return R.drawable.flag_guyane; case "ht": //haiti return R.drawable.flag_haiti; case "hn": //honduras return R.drawable.flag_honduras; case "hk": //hong kong return R.drawable.flag_hong_kong; case "hu": //hungary return R.drawable.flag_hungary; case "in": //india return R.drawable.flag_india; case "id": //indonesia return R.drawable.flag_indonesia; case "ir": //iran, islamic republic of return R.drawable.flag_iran; case "iq": //iraq return R.drawable.flag_iraq; case "ie": //ireland return R.drawable.flag_ireland; case "im": //isle of man return R.drawable.flag_isleof_man; // custom case "il": //israel return R.drawable.flag_israel; case "it": //italy return R.drawable.flag_italy; case "ci": return R.drawable.flag_cote_divoire; case "jp": //japan return R.drawable.flag_japan; case "jo": //jordan return R.drawable.flag_jordan; case "kz": //kazakhstan return R.drawable.flag_kazakhstan; case "ke": //kenya return R.drawable.flag_kenya; case "ki": //kiribati return R.drawable.flag_kiribati; case "kw": //kuwait return R.drawable.flag_kuwait; case "kg": //kyrgyzstan return R.drawable.flag_kyrgyzstan; case "ky": // Cayman Islands return R.drawable.flag_cayman_islands; case "la": //lao people\'s democratic republic return R.drawable.flag_laos; case "lv": //latvia return R.drawable.flag_latvia; case "lb": //lebanon return R.drawable.flag_lebanon; case "ls": //lesotho return R.drawable.flag_lesotho; case "lr": //liberia return R.drawable.flag_liberia; case "ly": //libya return R.drawable.flag_libya; case "li": //liechtenstein return R.drawable.flag_liechtenstein; case "lt": //lithuania return R.drawable.flag_lithuania; case "lu": //luxembourg return R.drawable.flag_luxembourg; case "mo": //macao return R.drawable.flag_macao; case "mk": //macedonia, the former yugoslav republic of return R.drawable.flag_macedonia; case "mg": //madagascar return R.drawable.flag_madagascar; case "mw": //malawi return R.drawable.flag_malawi; case "my": //malaysia return R.drawable.flag_malaysia; case "mv": //maldives return R.drawable.flag_maldives; case "ml": //mali return R.drawable.flag_mali; case "mt": //malta return R.drawable.flag_malta; case "mh": //marshall islands return R.drawable.flag_marshall_islands; case "mr": //mauritania return R.drawable.flag_mauritania; case "mu": //mauritius return R.drawable.flag_mauritius; case "yt": //mayotte return R.drawable.flag_martinique; // no exact flag found case "re": //la reunion return R.drawable.flag_martinique; // no exact flag found case "mq": //martinique return R.drawable.flag_martinique; case "mx": //mexico return R.drawable.flag_mexico; case "fm": //micronesia, federated states of return R.drawable.flag_micronesia; case "md": //moldova, republic of return R.drawable.flag_moldova; case "mc": //monaco return R.drawable.flag_monaco; case "mn": //mongolia return R.drawable.flag_mongolia; case "me": //montenegro return R.drawable.flag_of_montenegro;// custom case "ma": //morocco return R.drawable.flag_morocco; case "mz": //mozambique return R.drawable.flag_mozambique; case "na": //namibia return R.drawable.flag_namibia; case "nr": //nauru return R.drawable.flag_nauru; case "np": //nepal return R.drawable.flag_nepal; case "nl": //netherlands return R.drawable.flag_netherlands; case "nc": //new caledonia return R.drawable.flag_new_caledonia;// custom case "nz": //new zealand return R.drawable.flag_new_zealand; case "ni": //nicaragua return R.drawable.flag_nicaragua; case "ne": //niger return R.drawable.flag_niger; case "ng": //nigeria return R.drawable.flag_nigeria; case "nu": //niue return R.drawable.flag_niue; case "kp": //north korea return R.drawable.flag_north_korea; case "no": //norway return R.drawable.flag_norway; case "om": //oman return R.drawable.flag_oman; case "pk": //pakistan return R.drawable.flag_pakistan; case "pw": //palau return R.drawable.flag_palau; case "pa": //panama return R.drawable.flag_panama; case "pg": //papua new guinea return R.drawable.flag_papua_new_guinea; case "py": //paraguay return R.drawable.flag_paraguay; case "pe": //peru return R.drawable.flag_peru; case "ph": //philippines return R.drawable.flag_philippines; case "pn": //pitcairn return R.drawable.flag_pitcairn_islands; case "pl": //poland return R.drawable.flag_poland; case "pt": //portugal return R.drawable.flag_portugal; case "pr": //puerto rico return R.drawable.flag_puerto_rico; case "qa": //qatar return R.drawable.flag_qatar; case "ro": //romania return R.drawable.flag_romania; case "ru": //russian federation return R.drawable.flag_russian_federation; case "rw": //rwanda return R.drawable.flag_rwanda; case "bl": return R.drawable.flag_saint_barthelemy;// custom case "ws": //samoa return R.drawable.flag_samoa; case "sm": //san marino return R.drawable.flag_san_marino; case "st": //sao tome and principe return R.drawable.flag_sao_tome_and_principe; case "sa": //saudi arabia return R.drawable.flag_saudi_arabia; case "sn": //senegal return R.drawable.flag_senegal; case "rs": //serbia return R.drawable.flag_serbia; // custom case "sc": //seychelles return R.drawable.flag_seychelles; case "sl": //sierra leone return R.drawable.flag_sierra_leone; case "sg": //singapore return R.drawable.flag_singapore; case "sx": // Sint Maarten //TODO: Add Flag. return 0; case "sk": //slovakia return R.drawable.flag_slovakia; case "si": //slovenia return R.drawable.flag_slovenia; case "sb": //solomon islands return R.drawable.flag_soloman_islands; case "so": //somalia return R.drawable.flag_somalia; case "za": //south africa return R.drawable.flag_south_africa; case "kr": //south korea return R.drawable.flag_south_korea; case "es": //spain return R.drawable.flag_spain; case "lk": //sri lanka return R.drawable.flag_sri_lanka; case "sh": //saint helena, ascension and tristan da cunha return R.drawable.flag_saint_helena; // custom case "pm": //saint pierre and miquelon return R.drawable.flag_saint_pierre; case "sd": //sudan return R.drawable.flag_sudan; case "sr": //suriname return R.drawable.flag_suriname; case "sz": //swaziland return R.drawable.flag_swaziland; case "se": //sweden return R.drawable.flag_sweden; case "ch": //switzerland return R.drawable.flag_switzerland; case "sy": //syrian arab republic return R.drawable.flag_syria; case "tw": //taiwan, province of china return R.drawable.flag_taiwan; case "tj": //tajikistan return R.drawable.flag_tajikistan; case "tz": //tanzania, united republic of return R.drawable.flag_tanzania; case "th": //thailand return R.drawable.flag_thailand; case "tg": //togo return R.drawable.flag_togo; case "tk": //tokelau return R.drawable.flag_tokelau; // custom case "to": //tonga return R.drawable.flag_tonga; case "tn": //tunisia return R.drawable.flag_tunisia; case "tr": //turkey return R.drawable.flag_turkey; case "tm": //turkmenistan return R.drawable.flag_turkmenistan; case "tv": //tuvalu return R.drawable.flag_tuvalu; case "ae": //united arab emirates return R.drawable.flag_uae; case "ug": //uganda return R.drawable.flag_uganda; case "gb": //united kingdom return R.drawable.flag_united_kingdom; case "ua": //ukraine return R.drawable.flag_ukraine; case "uy": //uruguay return R.drawable.flag_uruguay; case "us": //united states return R.drawable.flag_united_states_of_america; case "uz": //uzbekistan return R.drawable.flag_uzbekistan; case "vu": //vanuatu return R.drawable.flag_vanuatu; case "va": //holy see (vatican city state) return R.drawable.flag_vatican_city; case "ve": //venezuela, bolivarian republic of return R.drawable.flag_venezuela; case "vn": //vietnam return R.drawable.flag_vietnam; case "wf": //wallis and futuna return R.drawable.flag_wallis_and_futuna; case "ye": //yemen return R.drawable.flag_yemen; case "zm": //zambia return R.drawable.flag_zambia; case "zw": //zimbabwe return R.drawable.flag_zimbabwe; // Caribbean Islands case "ai": //anguilla return R.drawable.flag_anguilla; case "ag": //antigua & barbuda return R.drawable.flag_antigua_and_barbuda; case "bs": //bahamas return R.drawable.flag_bahamas; case "bb": //barbados return R.drawable.flag_barbados; case "bm": //bermuda return R.drawable.flag_bermuda; case "vg": //british virgin islands return R.drawable.flag_british_virgin_islands; case "dm": //dominica return R.drawable.flag_dominica; case "do": //dominican republic return R.drawable.flag_dominican_republic; case "gd": //grenada return R.drawable.flag_grenada; case "jm": //jamaica return R.drawable.flag_jamaica; case "ms": //montserrat return R.drawable.flag_montserrat; case "kn": //st kitts & nevis return R.drawable.flag_saint_kitts_and_nevis; case "lc": //st lucia return R.drawable.flag_saint_lucia; case "vc": //st vincent & the grenadines return R.drawable.flag_saint_vicent_and_the_grenadines; case "tt": //trinidad & tobago return R.drawable.flag_trinidad_and_tobago; case "tc": //turks & caicos islands return R.drawable.flag_turks_and_caicos_islands; case "vi": //us virgin islands return R.drawable.flag_us_virgin_islands; case "ss": // south sudan return R.drawable.flag_south_sudan; case "xk": // kosovo return R.drawable.flag_kosovo; case "is": // iceland return R.drawable.flag_iceland; case "ax": //aland islands return R.drawable.flag_aland_islands; case "as": //american samoa return R.drawable.flag_american_samoa; case "io": //british indian ocean territory return R.drawable.flag_british_indian_ocean_territory; case "gp": //guadeloupe return R.drawable.flag_guadeloupe; case "gu": //guam return R.drawable.flag_guam; case "gg": //guernsey return R.drawable.flag_guernsey; case "je": //jersey return R.drawable.flag_jersey; case "nf": //norfolk island return R.drawable.flag_norfolk_island; case "mp": //northern mariana islands return R.drawable.flag_northern_mariana_islands; case "ps": //palestian territory return R.drawable.flag_palestian_territory; case "mf": //saint martin return R.drawable.flag_saint_martin; case "gs": //south georgia return R.drawable.flag_south_georgia; default: return R.drawable.flag_transparent; } } /** * Get all countries * @param context caller context * @return List of Country */ static List<Country> getAllCountries(Context context) { if(countries != null) return countries; countries = new ArrayList<>(); countries.add(new Country(context.getString(R.string.country_afghanistan_code), context.getString(R.string.country_afghanistan_number), context.getString(R.string.country_afghanistan_name))); countries.add(new Country(context.getString(R.string.country_albania_code), context.getString(R.string.country_albania_number), context.getString(R.string.country_albania_name))); countries.add(new Country(context.getString(R.string.country_algeria_code), context.getString(R.string.country_algeria_number), context.getString(R.string.country_algeria_name))); countries.add(new Country(context.getString(R.string.country_andorra_code), context.getString(R.string.country_andorra_number), context.getString(R.string.country_andorra_name))); countries.add(new Country(context.getString(R.string.country_angola_code), context.getString(R.string.country_angola_number), context.getString(R.string.country_angola_name))); countries.add(new Country(context.getString(R.string.country_anguilla_code), context.getString(R.string.country_anguilla_number), context.getString(R.string.country_anguilla_name))); countries.add(new Country(context.getString(R.string.country_antarctica_code), context.getString(R.string.country_antarctica_number), context.getString(R.string.country_antarctica_name))); countries.add(new Country(context.getString(R.string.country_antigua_and_barbuda_code), context.getString(R.string.country_antigua_and_barbuda_number), context.getString(R.string.country_antigua_and_barbuda_name))); countries.add(new Country(context.getString(R.string.country_argentina_code), context.getString(R.string.country_argentina_number), context.getString(R.string.country_argentina_name))); countries.add(new Country(context.getString(R.string.country_armenia_code), context.getString(R.string.country_armenia_number), context.getString(R.string.country_armenia_name))); countries.add(new Country(context.getString(R.string.country_aruba_code), context.getString(R.string.country_aruba_number), context.getString(R.string.country_aruba_name))); countries.add(new Country(context.getString(R.string.country_australia_code), context.getString(R.string.country_australia_number), context.getString(R.string.country_australia_name))); countries.add(new Country(context.getString(R.string.country_austria_code), context.getString(R.string.country_austria_number), context.getString(R.string.country_austria_name))); countries.add(new Country(context.getString(R.string.country_azerbaijan_code), context.getString(R.string.country_azerbaijan_number), context.getString(R.string.country_azerbaijan_name))); countries.add(new Country(context.getString(R.string.country_bahamas_code), context.getString(R.string.country_bahamas_number), context.getString(R.string.country_bahamas_name))); countries.add(new Country(context.getString(R.string.country_bahrain_code), context.getString(R.string.country_bahrain_number), context.getString(R.string.country_bahrain_name))); countries.add(new Country(context.getString(R.string.country_bangladesh_code), context.getString(R.string.country_bangladesh_number), context.getString(R.string.country_bangladesh_name))); countries.add(new Country(context.getString(R.string.country_barbados_code), context.getString(R.string.country_barbados_number), context.getString(R.string.country_barbados_name))); countries.add(new Country(context.getString(R.string.country_belarus_code), context.getString(R.string.country_belarus_number), context.getString(R.string.country_belarus_name))); countries.add(new Country(context.getString(R.string.country_belgium_code), context.getString(R.string.country_belgium_number), context.getString(R.string.country_belgium_name))); countries.add(new Country(context.getString(R.string.country_belize_code), context.getString(R.string.country_belize_number), context.getString(R.string.country_belize_name))); countries.add(new Country(context.getString(R.string.country_benin_code), context.getString(R.string.country_benin_number), context.getString(R.string.country_benin_name))); countries.add(new Country(context.getString(R.string.country_bermuda_code), context.getString(R.string.country_bermuda_number), context.getString(R.string.country_bermuda_name))); countries.add(new Country(context.getString(R.string.country_bhutan_code), context.getString(R.string.country_bhutan_number), context.getString(R.string.country_bhutan_name))); countries.add(new Country(context.getString(R.string.country_bolivia_code), context.getString(R.string.country_bolivia_number), context.getString(R.string.country_bolivia_name))); countries.add(new Country(context.getString(R.string.country_bosnia_and_herzegovina_code), context.getString(R.string.country_bosnia_and_herzegovina_number), context.getString(R.string.country_bosnia_and_herzegovina_name))); countries.add(new Country(context.getString(R.string.country_botswana_code), context.getString(R.string.country_botswana_number), context.getString(R.string.country_botswana_name))); countries.add(new Country(context.getString(R.string.country_brazil_code), context.getString(R.string.country_brazil_number), context.getString(R.string.country_brazil_name))); countries.add(new Country(context.getString(R.string.country_british_virgin_islands_code), context.getString(R.string.country_british_virgin_islands_number), context.getString(R.string.country_british_virgin_islands_name))); countries.add(new Country(context.getString(R.string.country_brunei_darussalam_code), context.getString(R.string.country_brunei_darussalam_number), context.getString(R.string.country_brunei_darussalam_name))); countries.add(new Country(context.getString(R.string.country_bulgaria_code), context.getString(R.string.country_bulgaria_number), context.getString(R.string.country_bulgaria_name))); countries.add(new Country(context.getString(R.string.country_burkina_faso_code), context.getString(R.string.country_burkina_faso_number), context.getString(R.string.country_burkina_faso_name))); countries.add(new Country(context.getString(R.string.country_burundi_code), context.getString(R.string.country_burundi_number), context.getString(R.string.country_burundi_name))); countries.add(new Country(context.getString(R.string.country_cambodia_code), context.getString(R.string.country_cambodia_number), context.getString(R.string.country_cambodia_name))); countries.add(new Country(context.getString(R.string.country_cameroon_code), context.getString(R.string.country_cameroon_number), context.getString(R.string.country_cameroon_name))); countries.add(new Country(context.getString(R.string.country_canada_code), context.getString(R.string.country_canada_number), context.getString(R.string.country_canada_name))); countries.add(new Country(context.getString(R.string.country_cape_verde_code), context.getString(R.string.country_cape_verde_number), context.getString(R.string.country_cape_verde_name))); countries.add(new Country(context.getString(R.string.country_cayman_islands_code), context.getString(R.string.country_cayman_islands_number), context.getString(R.string.country_cayman_islands_name))); countries.add(new Country(context.getString(R.string.country_central_african_republic_code), context.getString(R.string.country_central_african_republic_number), context.getString(R.string.country_central_african_republic_name))); countries.add(new Country(context.getString(R.string.country_chad_code), context.getString(R.string.country_chad_number), context.getString(R.string.country_chad_name))); countries.add(new Country(context.getString(R.string.country_chile_code), context.getString(R.string.country_chile_number), context.getString(R.string.country_chile_name))); countries.add(new Country(context.getString(R.string.country_china_code), context.getString(R.string.country_china_number), context.getString(R.string.country_china_name))); countries.add(new Country(context.getString(R.string.country_christmas_island_code), context.getString(R.string.country_christmas_island_number), context.getString(R.string.country_christmas_island_name))); countries.add(new Country(context.getString(R.string.country_cocos_keeling_islands_code), context.getString(R.string.country_cocos_keeling_islands_number), context.getString(R.string.country_cocos_keeling_islands_name))); countries.add(new Country(context.getString(R.string.country_colombia_code), context.getString(R.string.country_colombia_number), context.getString(R.string.country_colombia_name))); countries.add(new Country(context.getString(R.string.country_comoros_code), context.getString(R.string.country_comoros_number), context.getString(R.string.country_comoros_name))); countries.add(new Country(context.getString(R.string.country_congo_code), context.getString(R.string.country_congo_number), context.getString(R.string.country_congo_name))); countries.add(new Country(context.getString(R.string.country_the_democratic_republic_of_congo_code), context.getString(R.string.country_the_democratic_republic_of_congo_number), context.getString(R.string.country_the_democratic_republic_of_congo_name))); countries.add(new Country(context.getString(R.string.country_cook_islands_code), context.getString(R.string.country_cook_islands_number), context.getString(R.string.country_cook_islands_name))); countries.add(new Country(context.getString(R.string.country_costa_rica_code), context.getString(R.string.country_costa_rica_number), context.getString(R.string.country_costa_rica_name))); countries.add(new Country(context.getString(R.string.country_croatia_code), context.getString(R.string.country_croatia_number), context.getString(R.string.country_croatia_name))); countries.add(new Country(context.getString(R.string.country_cuba_code), context.getString(R.string.country_cuba_number), context.getString(R.string.country_cuba_name))); countries.add(new Country(context.getString(R.string.country_cyprus_code), context.getString(R.string.country_cyprus_number), context.getString(R.string.country_cyprus_name))); countries.add(new Country(context.getString(R.string.country_czech_republic_code), context.getString(R.string.country_czech_republic_number), context.getString(R.string.country_czech_republic_name))); countries.add(new Country(context.getString(R.string.country_denmark_code), context.getString(R.string.country_denmark_number), context.getString(R.string.country_denmark_name))); countries.add(new Country(context.getString(R.string.country_djibouti_code), context.getString(R.string.country_djibouti_number), context.getString(R.string.country_djibouti_name))); countries.add(new Country(context.getString(R.string.country_dominica_code), context.getString(R.string.country_dominica_number), context.getString(R.string.country_dominica_name))); countries.add(new Country(context.getString(R.string.country_dominican_republic_code), context.getString(R.string.country_dominican_republic_number), context.getString(R.string.country_dominican_republic_name))); countries.add(new Country(context.getString(R.string.country_timor_leste_code), context.getString(R.string.country_timor_leste_number), context.getString(R.string.country_timor_leste_name))); countries.add(new Country(context.getString(R.string.country_ecuador_code), context.getString(R.string.country_ecuador_number), context.getString(R.string.country_ecuador_name))); countries.add(new Country(context.getString(R.string.country_egypt_code), context.getString(R.string.country_egypt_number), context.getString(R.string.country_egypt_name))); countries.add(new Country(context.getString(R.string.country_el_salvador_code), context.getString(R.string.country_el_salvador_number), context.getString(R.string.country_el_salvador_name))); countries.add(new Country(context.getString(R.string.country_equatorial_guinea_code), context.getString(R.string.country_equatorial_guinea_number), context.getString(R.string.country_equatorial_guinea_name))); countries.add(new Country(context.getString(R.string.country_eritrea_code), context.getString(R.string.country_eritrea_number), context.getString(R.string.country_eritrea_name))); countries.add(new Country(context.getString(R.string.country_estonia_code), context.getString(R.string.country_estonia_number), context.getString(R.string.country_estonia_name))); countries.add(new Country(context.getString(R.string.country_ethiopia_code), context.getString(R.string.country_ethiopia_number), context.getString(R.string.country_ethiopia_name))); countries.add(new Country(context.getString(R.string.country_falkland_islands_malvinas_code), context.getString(R.string.country_falkland_islands_malvinas_number), context.getString(R.string.country_falkland_islands_malvinas_name))); countries.add(new Country(context.getString(R.string.country_faroe_islands_code), context.getString(R.string.country_faroe_islands_number), context.getString(R.string.country_faroe_islands_name))); countries.add(new Country(context.getString(R.string.country_fiji_code), context.getString(R.string.country_fiji_number), context.getString(R.string.country_fiji_name))); countries.add(new Country(context.getString(R.string.country_finland_code), context.getString(R.string.country_finland_number), context.getString(R.string.country_finland_name))); countries.add(new Country(context.getString(R.string.country_france_code), context.getString(R.string.country_france_number), context.getString(R.string.country_france_name))); countries.add(new Country(context.getString(R.string.country_french_guyana_code), context.getString(R.string.country_french_guyana_number), context.getString(R.string.country_french_guyana_name))); countries.add(new Country(context.getString(R.string.country_french_polynesia_code), context.getString(R.string.country_french_polynesia_number), context.getString(R.string.country_french_polynesia_name))); countries.add(new Country(context.getString(R.string.country_gabon_code), context.getString(R.string.country_gabon_number), context.getString(R.string.country_gabon_name))); countries.add(new Country(context.getString(R.string.country_gambia_code), context.getString(R.string.country_gambia_number), context.getString(R.string.country_gambia_name))); countries.add(new Country(context.getString(R.string.country_georgia_code), context.getString(R.string.country_georgia_number), context.getString(R.string.country_georgia_name))); countries.add(new Country(context.getString(R.string.country_germany_code), context.getString(R.string.country_germany_number), context.getString(R.string.country_germany_name))); countries.add(new Country(context.getString(R.string.country_ghana_code), context.getString(R.string.country_ghana_number), context.getString(R.string.country_ghana_name))); countries.add(new Country(context.getString(R.string.country_gibraltar_code), context.getString(R.string.country_gibraltar_number), context.getString(R.string.country_gibraltar_name))); countries.add(new Country(context.getString(R.string.country_greece_code), context.getString(R.string.country_greece_number), context.getString(R.string.country_greece_name))); countries.add(new Country(context.getString(R.string.country_greenland_code), context.getString(R.string.country_greenland_number), context.getString(R.string.country_greenland_name))); countries.add(new Country(context.getString(R.string.country_grenada_code), context.getString(R.string.country_grenada_number), context.getString(R.string.country_grenada_name))); countries.add(new Country(context.getString(R.string.country_guatemala_code), context.getString(R.string.country_guatemala_number), context.getString(R.string.country_guatemala_name))); countries.add(new Country(context.getString(R.string.country_guinea_code), context.getString(R.string.country_guinea_number), context.getString(R.string.country_guinea_name))); countries.add(new Country(context.getString(R.string.country_guinea_bissau_code), context.getString(R.string.country_guinea_bissau_number), context.getString(R.string.country_guinea_bissau_name))); countries.add(new Country(context.getString(R.string.country_guyana_code), context.getString(R.string.country_guyana_number), context.getString(R.string.country_guyana_name))); countries.add(new Country(context.getString(R.string.country_haiti_code), context.getString(R.string.country_haiti_number), context.getString(R.string.country_haiti_name))); countries.add(new Country(context.getString(R.string.country_honduras_code), context.getString(R.string.country_honduras_number), context.getString(R.string.country_honduras_name))); countries.add(new Country(context.getString(R.string.country_hong_kong_code), context.getString(R.string.country_hong_kong_number), context.getString(R.string.country_hong_kong_name))); countries.add(new Country(context.getString(R.string.country_hungary_code), context.getString(R.string.country_hungary_number), context.getString(R.string.country_hungary_name))); countries.add(new Country(context.getString(R.string.country_iceland_code), context.getString(R.string.country_iceland_number), context.getString(R.string.country_iceland_name))); countries.add(new Country(context.getString(R.string.country_india_code), context.getString(R.string.country_india_number), context.getString(R.string.country_india_name))); countries.add(new Country(context.getString(R.string.country_indonesia_code), context.getString(R.string.country_indonesia_number), context.getString(R.string.country_indonesia_name))); countries.add(new Country(context.getString(R.string.country_iran_code), context.getString(R.string.country_iran_number), context.getString(R.string.country_iran_name))); countries.add(new Country(context.getString(R.string.country_iraq_code), context.getString(R.string.country_iraq_number), context.getString(R.string.country_iraq_name))); countries.add(new Country(context.getString(R.string.country_ireland_code), context.getString(R.string.country_ireland_number), context.getString(R.string.country_ireland_name))); countries.add(new Country(context.getString(R.string.country_isle_of_man_code), context.getString(R.string.country_isle_of_man_number), context.getString(R.string.country_isle_of_man_name))); countries.add(new Country(context.getString(R.string.country_israel_code), context.getString(R.string.country_israel_number), context.getString(R.string.country_israel_name))); countries.add(new Country(context.getString(R.string.country_italy_code), context.getString(R.string.country_italy_number), context.getString(R.string.country_italy_name))); countries.add(new Country(context.getString(R.string.country_cote_d_ivoire_code), context.getString(R.string.country_cote_d_ivoire_number), context.getString(R.string.country_cote_d_ivoire_name))); countries.add(new Country(context.getString(R.string.country_jamaica_code), context.getString(R.string.country_jamaica_number), context.getString(R.string.country_jamaica_name))); countries.add(new Country(context.getString(R.string.country_japan_code), context.getString(R.string.country_japan_number), context.getString(R.string.country_japan_name))); countries.add(new Country(context.getString(R.string.country_jordan_code), context.getString(R.string.country_jordan_number), context.getString(R.string.country_jordan_name))); countries.add(new Country(context.getString(R.string.country_kazakhstan_code), context.getString(R.string.country_kazakhstan_number), context.getString(R.string.country_kazakhstan_name))); countries.add(new Country(context.getString(R.string.country_kenya_code), context.getString(R.string.country_kenya_number), context.getString(R.string.country_kenya_name))); countries.add(new Country(context.getString(R.string.country_kiribati_code), context.getString(R.string.country_kiribati_number), context.getString(R.string.country_kiribati_name))); countries.add(new Country(context.getString(R.string.country_kosovo_code), context.getString(R.string.country_kosovo_number), context.getString(R.string.country_kosovo_name))); countries.add(new Country(context.getString(R.string.country_kuwait_code), context.getString(R.string.country_kuwait_number), context.getString(R.string.country_kuwait_name))); countries.add(new Country(context.getString(R.string.country_kyrgyzstan_code), context.getString(R.string.country_kyrgyzstan_number), context.getString(R.string.country_kyrgyzstan_name))); countries.add(new Country(context.getString(R.string.country_lao_peoples_democratic_republic_code), context.getString(R.string.country_lao_peoples_democratic_republic_number), context.getString(R.string.country_lao_peoples_democratic_republic_name))); countries.add(new Country(context.getString(R.string.country_latvia_code), context.getString(R.string.country_latvia_number), context.getString(R.string.country_latvia_name))); countries.add(new Country(context.getString(R.string.country_lebanon_code), context.getString(R.string.country_lebanon_number), context.getString(R.string.country_lebanon_name))); countries.add(new Country(context.getString(R.string.country_lesotho_code), context.getString(R.string.country_lesotho_number), context.getString(R.string.country_lesotho_name))); countries.add(new Country(context.getString(R.string.country_liberia_code), context.getString(R.string.country_liberia_number), context.getString(R.string.country_liberia_name))); countries.add(new Country(context.getString(R.string.country_libya_code), context.getString(R.string.country_libya_number), context.getString(R.string.country_libya_name))); countries.add(new Country(context.getString(R.string.country_liechtenstein_code), context.getString(R.string.country_liechtenstein_number), context.getString(R.string.country_liechtenstein_name))); countries.add(new Country(context.getString(R.string.country_lithuania_code), context.getString(R.string.country_lithuania_number), context.getString(R.string.country_lithuania_name))); countries.add(new Country(context.getString(R.string.country_luxembourg_code), context.getString(R.string.country_luxembourg_number), context.getString(R.string.country_luxembourg_name))); countries.add(new Country(context.getString(R.string.country_macao_code), context.getString(R.string.country_macao_number), context.getString(R.string.country_macao_name))); countries.add(new Country(context.getString(R.string.country_macedonia_code), context.getString(R.string.country_macedonia_number), context.getString(R.string.country_macedonia_name))); countries.add(new Country(context.getString(R.string.country_madagascar_code), context.getString(R.string.country_madagascar_number), context.getString(R.string.country_madagascar_name))); countries.add(new Country(context.getString(R.string.country_malawi_code), context.getString(R.string.country_malawi_number), context.getString(R.string.country_malawi_name))); countries.add(new Country(context.getString(R.string.country_malaysia_code), context.getString(R.string.country_malaysia_number), context.getString(R.string.country_malaysia_name))); countries.add(new Country(context.getString(R.string.country_maldives_code), context.getString(R.string.country_maldives_number), context.getString(R.string.country_maldives_name))); countries.add(new Country(context.getString(R.string.country_mali_code), context.getString(R.string.country_mali_number), context.getString(R.string.country_mali_name))); countries.add(new Country(context.getString(R.string.country_malta_code), context.getString(R.string.country_malta_number), context.getString(R.string.country_malta_name))); countries.add(new Country(context.getString(R.string.country_marshall_islands_code), context.getString(R.string.country_marshall_islands_number), context.getString(R.string.country_marshall_islands_name))); countries.add(new Country(context.getString(R.string.country_martinique_code), context.getString(R.string.country_martinique_number), context.getString(R.string.country_martinique_name))); countries.add(new Country(context.getString(R.string.country_mauritania_code), context.getString(R.string.country_mauritania_number), context.getString(R.string.country_mauritania_name))); countries.add(new Country(context.getString(R.string.country_mauritius_code), context.getString(R.string.country_mauritius_number), context.getString(R.string.country_mauritius_name))); countries.add(new Country(context.getString(R.string.country_mayotte_code), context.getString(R.string.country_mayotte_number), context.getString(R.string.country_mayotte_name))); countries.add(new Country(context.getString(R.string.country_mexico_code), context.getString(R.string.country_mexico_number), context.getString(R.string.country_mexico_name))); countries.add(new Country(context.getString(R.string.country_micronesia_code), context.getString(R.string.country_micronesia_number), context.getString(R.string.country_micronesia_name))); countries.add(new Country(context.getString(R.string.country_moldova_code), context.getString(R.string.country_moldova_number), context.getString(R.string.country_moldova_name))); countries.add(new Country(context.getString(R.string.country_monaco_code), context.getString(R.string.country_monaco_number), context.getString(R.string.country_monaco_name))); countries.add(new Country(context.getString(R.string.country_mongolia_code), context.getString(R.string.country_mongolia_number), context.getString(R.string.country_mongolia_name))); countries.add(new Country(context.getString(R.string.country_montserrat_code), context.getString(R.string.country_montserrat_number), context.getString(R.string.country_montserrat_name))); countries.add(new Country(context.getString(R.string.country_montenegro_code), context.getString(R.string.country_montenegro_number), context.getString(R.string.country_montenegro_name))); countries.add(new Country(context.getString(R.string.country_morocco_code), context.getString(R.string.country_morocco_number), context.getString(R.string.country_morocco_name))); countries.add(new Country(context.getString(R.string.country_myanmar_code), context.getString(R.string.country_myanmar_number), context.getString(R.string.country_myanmar_name))); countries.add(new Country(context.getString(R.string.country_mozambique_code), context.getString(R.string.country_mozambique_number), context.getString(R.string.country_mozambique_name))); countries.add(new Country(context.getString(R.string.country_namibia_code), context.getString(R.string.country_namibia_number), context.getString(R.string.country_namibia_name))); countries.add(new Country(context.getString(R.string.country_nauru_code), context.getString(R.string.country_nauru_number), context.getString(R.string.country_nauru_name))); countries.add(new Country(context.getString(R.string.country_nepal_code), context.getString(R.string.country_nepal_number), context.getString(R.string.country_nepal_name))); countries.add(new Country(context.getString(R.string.country_netherlands_code), context.getString(R.string.country_netherlands_number), context.getString(R.string.country_netherlands_name))); countries.add(new Country(context.getString(R.string.country_new_caledonia_code), context.getString(R.string.country_new_caledonia_number), context.getString(R.string.country_new_caledonia_name))); countries.add(new Country(context.getString(R.string.country_new_zealand_code), context.getString(R.string.country_new_zealand_number), context.getString(R.string.country_new_zealand_name))); countries.add(new Country(context.getString(R.string.country_nicaragua_code), context.getString(R.string.country_nicaragua_number), context.getString(R.string.country_nicaragua_name))); countries.add(new Country(context.getString(R.string.country_niger_code), context.getString(R.string.country_niger_number), context.getString(R.string.country_niger_name))); countries.add(new Country(context.getString(R.string.country_nigeria_code), context.getString(R.string.country_nigeria_number), context.getString(R.string.country_nigeria_name))); countries.add(new Country(context.getString(R.string.country_niue_code), context.getString(R.string.country_niue_number), context.getString(R.string.country_niue_name))); countries.add(new Country(context.getString(R.string.country_north_korea_code), context.getString(R.string.country_north_korea_number), context.getString(R.string.country_north_korea_name))); countries.add(new Country(context.getString(R.string.country_norway_code), context.getString(R.string.country_norway_number), context.getString(R.string.country_norway_name))); countries.add(new Country(context.getString(R.string.country_oman_code), context.getString(R.string.country_oman_number), context.getString(R.string.country_oman_name))); countries.add(new Country(context.getString(R.string.country_pakistan_code), context.getString(R.string.country_pakistan_number), context.getString(R.string.country_pakistan_name))); countries.add(new Country(context.getString(R.string.country_palau_code), context.getString(R.string.country_palau_number), context.getString(R.string.country_palau_name))); countries.add(new Country(context.getString(R.string.country_panama_code), context.getString(R.string.country_panama_number), context.getString(R.string.country_panama_name))); countries.add(new Country(context.getString(R.string.country_papua_new_guinea_code), context.getString(R.string.country_papua_new_guinea_number), context.getString(R.string.country_papua_new_guinea_name))); countries.add(new Country(context.getString(R.string.country_paraguay_code), context.getString(R.string.country_paraguay_number), context.getString(R.string.country_paraguay_name))); countries.add(new Country(context.getString(R.string.country_peru_code), context.getString(R.string.country_peru_number), context.getString(R.string.country_peru_name))); countries.add(new Country(context.getString(R.string.country_philippines_code), context.getString(R.string.country_philippines_number), context.getString(R.string.country_philippines_name))); countries.add(new Country(context.getString(R.string.country_pitcairn_code), context.getString(R.string.country_pitcairn_number), context.getString(R.string.country_pitcairn_name))); countries.add(new Country(context.getString(R.string.country_poland_code), context.getString(R.string.country_poland_number), context.getString(R.string.country_poland_name))); countries.add(new Country(context.getString(R.string.country_portugal_code), context.getString(R.string.country_portugal_number), context.getString(R.string.country_portugal_name))); countries.add(new Country(context.getString(R.string.country_puerto_rico_code), context.getString(R.string.country_puerto_rico_number), context.getString(R.string.country_puerto_rico_name))); countries.add(new Country(context.getString(R.string.country_qatar_code), context.getString(R.string.country_qatar_number), context.getString(R.string.country_qatar_name))); countries.add(new Country(context.getString(R.string.country_reunion_code), context.getString(R.string.country_reunion_number), context.getString(R.string.country_reunion_name))); countries.add(new Country(context.getString(R.string.country_romania_code), context.getString(R.string.country_romania_number), context.getString(R.string.country_romania_name))); countries.add(new Country(context.getString(R.string.country_russian_federation_code), context.getString(R.string.country_russian_federation_number), context.getString(R.string.country_russian_federation_name))); countries.add(new Country(context.getString(R.string.country_rwanda_code), context.getString(R.string.country_rwanda_number), context.getString(R.string.country_rwanda_name))); countries.add(new Country(context.getString(R.string.country_saint_barthelemy_code), context.getString(R.string.country_saint_barthelemy_number), context.getString(R.string.country_saint_barthelemy_name))); countries.add(new Country(context.getString(R.string.country_saint_kitts_and_nevis_code), context.getString(R.string.country_saint_kitts_and_nevis_number), context.getString(R.string.country_saint_kitts_and_nevis_name))); countries.add(new Country(context.getString(R.string.country_saint_lucia_code), context.getString(R.string.country_saint_lucia_number), context.getString(R.string.country_saint_lucia_name))); countries.add(new Country(context.getString(R.string.country_saint_vincent_the_grenadines_code), context.getString(R.string.country_saint_vincent_the_grenadines_number), context.getString(R.string.country_saint_vincent_the_grenadines_name))); countries.add(new Country(context.getString(R.string.country_samoa_code), context.getString(R.string.country_samoa_number), context.getString(R.string.country_samoa_name))); countries.add(new Country(context.getString(R.string.country_san_marino_code), context.getString(R.string.country_san_marino_number), context.getString(R.string.country_san_marino_name))); countries.add(new Country(context.getString(R.string.country_sao_tome_and_principe_code), context.getString(R.string.country_sao_tome_and_principe_number), context.getString(R.string.country_sao_tome_and_principe_name))); countries.add(new Country(context.getString(R.string.country_saudi_arabia_code), context.getString(R.string.country_saudi_arabia_number), context.getString(R.string.country_saudi_arabia_name))); countries.add(new Country(context.getString(R.string.country_senegal_code), context.getString(R.string.country_senegal_number), context.getString(R.string.country_senegal_name))); countries.add(new Country(context.getString(R.string.country_serbia_code), context.getString(R.string.country_serbia_number), context.getString(R.string.country_serbia_name))); countries.add(new Country(context.getString(R.string.country_seychelles_code), context.getString(R.string.country_seychelles_number), context.getString(R.string.country_seychelles_name))); countries.add(new Country(context.getString(R.string.country_sierra_leone_code), context.getString(R.string.country_sierra_leone_number), context.getString(R.string.country_sierra_leone_name))); countries.add(new Country(context.getString(R.string.country_singapore_code), context.getString(R.string.country_singapore_number), context.getString(R.string.country_singapore_name))); countries.add(new Country(context.getString(R.string.country_sint_maarten_code), context.getString(R.string.country_sint_maarten_number), context.getString(R.string.country_sint_maarten_name))); countries.add(new Country(context.getString(R.string.country_slovakia_code), context.getString(R.string.country_slovakia_number), context.getString(R.string.country_slovakia_name))); countries.add(new Country(context.getString(R.string.country_slovenia_code), context.getString(R.string.country_slovenia_number), context.getString(R.string.country_slovenia_name))); countries.add(new Country(context.getString(R.string.country_solomon_islands_code), context.getString(R.string.country_solomon_islands_number), context.getString(R.string.country_solomon_islands_name))); countries.add(new Country(context.getString(R.string.country_somalia_code), context.getString(R.string.country_somalia_number), context.getString(R.string.country_somalia_name))); countries.add(new Country(context.getString(R.string.country_south_africa_code), context.getString(R.string.country_south_africa_number), context.getString(R.string.country_south_africa_name))); countries.add(new Country(context.getString(R.string.country_south_korea_code), context.getString(R.string.country_south_korea_number), context.getString(R.string.country_south_korea_name))); countries.add(new Country(context.getString(R.string.country_spain_code), context.getString(R.string.country_spain_number), context.getString(R.string.country_spain_name))); countries.add(new Country(context.getString(R.string.country_sri_lanka_code), context.getString(R.string.country_sri_lanka_number), context.getString(R.string.country_sri_lanka_name))); countries.add(new Country(context.getString(R.string.country_saint_helena_code), context.getString(R.string.country_saint_helena_number), context.getString(R.string.country_saint_helena_name))); countries.add(new Country(context.getString(R.string.country_saint_pierre_and_miquelon_code), context.getString(R.string.country_saint_pierre_and_miquelon_number), context.getString(R.string.country_saint_pierre_and_miquelon_name))); countries.add(new Country(context.getString(R.string.country_south_sudan_code), context.getString(R.string.country_south_sudan_number), context.getString(R.string.country_south_sudan_name))); countries.add(new Country(context.getString(R.string.country_sudan_code), context.getString(R.string.country_sudan_number), context.getString(R.string.country_sudan_name))); countries.add(new Country(context.getString(R.string.country_suriname_code), context.getString(R.string.country_suriname_number), context.getString(R.string.country_suriname_name))); countries.add(new Country(context.getString(R.string.country_swaziland_code), context.getString(R.string.country_swaziland_number), context.getString(R.string.country_swaziland_name))); countries.add(new Country(context.getString(R.string.country_sweden_code), context.getString(R.string.country_sweden_number), context.getString(R.string.country_sweden_name))); countries.add(new Country(context.getString(R.string.country_switzerland_code), context.getString(R.string.country_switzerland_number), context.getString(R.string.country_switzerland_name))); countries.add(new Country(context.getString(R.string.country_syrian_arab_republic_code), context.getString(R.string.country_syrian_arab_republic_number), context.getString(R.string.country_syrian_arab_republic_name))); countries.add(new Country(context.getString(R.string.country_taiwan_code), context.getString(R.string.country_taiwan_number), context.getString(R.string.country_taiwan_name))); countries.add(new Country(context.getString(R.string.country_tajikistan_code), context.getString(R.string.country_tajikistan_number), context.getString(R.string.country_tajikistan_name))); countries.add(new Country(context.getString(R.string.country_tanzania_code), context.getString(R.string.country_tanzania_number), context.getString(R.string.country_tanzania_name))); countries.add(new Country(context.getString(R.string.country_thailand_code), context.getString(R.string.country_thailand_number), context.getString(R.string.country_thailand_name))); countries.add(new Country(context.getString(R.string.country_togo_code), context.getString(R.string.country_togo_number), context.getString(R.string.country_togo_name))); countries.add(new Country(context.getString(R.string.country_tokelau_code), context.getString(R.string.country_tokelau_number), context.getString(R.string.country_tokelau_name))); countries.add(new Country(context.getString(R.string.country_tonga_code), context.getString(R.string.country_tonga_number), context.getString(R.string.country_tonga_name))); countries.add(new Country(context.getString(R.string.country_trinidad_tobago_code), context.getString(R.string.country_trinidad_tobago_number), context.getString(R.string.country_trinidad_tobago_name))); countries.add(new Country(context.getString(R.string.country_tunisia_code), context.getString(R.string.country_tunisia_number), context.getString(R.string.country_tunisia_name))); countries.add(new Country(context.getString(R.string.country_turkey_code), context.getString(R.string.country_turkey_number), context.getString(R.string.country_turkey_name))); countries.add(new Country(context.getString(R.string.country_turkmenistan_code), context.getString(R.string.country_turkmenistan_number), context.getString(R.string.country_turkmenistan_name))); countries.add(new Country(context.getString(R.string.country_turks_and_caicos_islands_code), context.getString(R.string.country_turks_and_caicos_islands_number), context.getString(R.string.country_turks_and_caicos_islands_name))); countries.add(new Country(context.getString(R.string.country_tuvalu_code), context.getString(R.string.country_tuvalu_number), context.getString(R.string.country_tuvalu_name))); countries.add(new Country(context.getString(R.string.country_united_arab_emirates_code), context.getString(R.string.country_united_arab_emirates_number), context.getString(R.string.country_united_arab_emirates_name))); countries.add(new Country(context.getString(R.string.country_uganda_code), context.getString(R.string.country_uganda_number), context.getString(R.string.country_uganda_name))); countries.add(new Country(context.getString(R.string.country_united_kingdom_code), context.getString(R.string.country_united_kingdom_number), context.getString(R.string.country_united_kingdom_name))); countries.add(new Country(context.getString(R.string.country_ukraine_code), context.getString(R.string.country_ukraine_number), context.getString(R.string.country_ukraine_name))); countries.add(new Country(context.getString(R.string.country_uruguay_code), context.getString(R.string.country_uruguay_number), context.getString(R.string.country_uruguay_name))); countries.add(new Country(context.getString(R.string.country_united_states_code), context.getString(R.string.country_united_states_number), context.getString(R.string.country_united_states_name))); countries.add(new Country(context.getString(R.string.country_us_virgin_islands_code), context.getString(R.string.country_us_virgin_islands_number), context.getString(R.string.country_us_virgin_islands_name))); countries.add(new Country(context.getString(R.string.country_uzbekistan_code), context.getString(R.string.country_uzbekistan_number), context.getString(R.string.country_uzbekistan_name))); countries.add(new Country(context.getString(R.string.country_vanuatu_code), context.getString(R.string.country_vanuatu_number), context.getString(R.string.country_vanuatu_name))); countries.add(new Country(context.getString(R.string.country_holy_see_vatican_city_state_code), context.getString(R.string.country_holy_see_vatican_city_state_number), context.getString(R.string.country_holy_see_vatican_city_state_name))); countries.add(new Country(context.getString(R.string.country_venezuela_code), context.getString(R.string.country_venezuela_number), context.getString(R.string.country_venezuela_name))); countries.add(new Country(context.getString(R.string.country_viet_nam_code), context.getString(R.string.country_viet_nam_number), context.getString(R.string.country_viet_nam_name))); countries.add(new Country(context.getString(R.string.country_wallis_and_futuna_code), context.getString(R.string.country_wallis_and_futuna_number), context.getString(R.string.country_wallis_and_futuna_name))); countries.add(new Country(context.getString(R.string.country_yemen_code), context.getString(R.string.country_yemen_number), context.getString(R.string.country_yemen_name))); countries.add(new Country(context.getString(R.string.country_zambia_code), context.getString(R.string.country_zambia_number), context.getString(R.string.country_zambia_name))); countries.add(new Country(context.getString(R.string.country_zimbabwe_code), context.getString(R.string.country_zimbabwe_number), context.getString(R.string.country_zimbabwe_name))); countries.add(new Country(context.getString(R.string.country_aland_islands_code), context.getString(R.string.country_aland_islands_number), context.getString(R.string.country_aland_islands_name))); countries.add(new Country(context.getString(R.string.country_american_samoa_code), context.getString(R.string.country_american_samoa_number), context.getString(R.string.country_american_samoa_name))); countries.add(new Country(context.getString(R.string.country_british_indian_ocean_territory_code), context.getString(R.string.country_british_indian_ocean_territory_number), context.getString(R.string.country_british_indian_ocean_territory_name))); countries.add(new Country(context.getString(R.string.country_guadeloupe_code), context.getString(R.string.country_guadeloupe_number), context.getString(R.string.country_guadeloupe_name))); countries.add(new Country(context.getString(R.string.country_guam_code), context.getString(R.string.country_guam_number), context.getString(R.string.country_guam_name))); countries.add(new Country(context.getString(R.string.country_guernsey_code), context.getString(R.string.country_guernsey_number), context.getString(R.string.country_guernsey_name))); countries.add(new Country(context.getString(R.string.country_jersey_code), context.getString(R.string.country_jersey_number), context.getString(R.string.country_jersey_name))); countries.add(new Country(context.getString(R.string.country_norfolk_island_code), context.getString(R.string.country_norfolk_island_number), context.getString(R.string.country_norfolk_island_name))); countries.add(new Country(context.getString(R.string.country_northern_mariana_islands_code), context.getString(R.string.country_northern_mariana_islands_number), context.getString(R.string.country_northern_mariana_islands_name))); countries.add(new Country(context.getString(R.string.country_palestian_territory_code), context.getString(R.string.country_palestian_territory_number), context.getString(R.string.country_palestian_territory_name))); countries.add(new Country(context.getString(R.string.country_saint_martin_code), context.getString(R.string.country_saint_martin_number), context.getString(R.string.country_saint_martin_name))); countries.add(new Country(context.getString(R.string.country_south_georgia_code), context.getString(R.string.country_south_georgia_number), context.getString(R.string.country_south_africa_name))); Collections.sort(countries, new Comparator<Country>() { @Override public int compare(Country country1, Country country2) { return country1.getName().compareToIgnoreCase(country2.getName()); } }); return countries; } /** * Finds country code by matching substring from left to right from full number. * For example. if full number is +819017901357 * function will ignore "+" and try to find match for first character "8" * if any country found for code "8", will return that country. If not, then it will * try to find country for "81". and so on till first 3 characters ( maximum number of characters * in country code is 3). * * @param preferredCountries countries of preference * @param fullNumber full number ( "+" (optional)+ country code + carrier number) i.e. * +819017901357 / 819017901357 / 918866667722 * @return Country JP +81(Japan) for +819017901357 or 819017901357 * Country IN +91(India) for 918866667722 * null for 2956635321 ( as neither of "2", "29" and "295" matches any country code) */ static Country getByNumber(Context context, List<Country> preferredCountries, String fullNumber) { int firstDigit; if (fullNumber.length() != 0) { if (fullNumber.charAt(0) == '+') { firstDigit = 1; } else { firstDigit = 0; } Country country; for (int i = firstDigit; i < firstDigit + 4; i++) { String code = fullNumber.substring(firstDigit, i); country = getByCode(context, preferredCountries, code); if (country != null) return country; } } return null; } /** * Search a country which matches @param code. * * @param preferredCountries list of country with priority, * @param code phone code. i.e 91 or 1 * @return Country that has phone code as @param code. * or returns null if no country matches given code. */ static Country getByCode(Context context, List<Country> preferredCountries, int code) { return getByCode(context, preferredCountries, code + ""); } /** * Search a country which matches @param code. * * @param preferredCountries is list of preference countries. * @param code phone code. i.e "91" or "1" * @return Country that has phone code as @param code. * or returns null if no country matches given code. * if same code (e.g. +1) available for more than one country ( US, canada) , this function will * return preferred country. */ private static Country getByCode(Context context, List<Country> preferredCountries, String code) { //check in preferred countries first if (preferredCountries != null && !preferredCountries.isEmpty()) { for (Country country : preferredCountries) { if (country.getPhoneCode().equals(code)) { return country; } } } for (Country country : CountryUtils.getAllCountries(context)) { if (country.getPhoneCode().equals(code)) { return country; } } return null; } /** * Search a country which matches @param nameCode. * * @param nameCode country name code. i.e US or us or Au. See countries.xml for all code names. * @return Country that has phone code as @param code. * or returns null if no country matches given code. */ static Country getByNameCodeFromCustomCountries(Context context, List<Country> customCountries, String nameCode) { if (customCountries == null || customCountries.size() == 0) { return getByNameCodeFromAllCountries(context, nameCode); } else { for (Country country : customCountries) { if (country.getIso().equalsIgnoreCase(nameCode)) { return country; } } } return null; } /** * Search a country which matches @param nameCode. * * @param nameCode country name code. i.e US or us or Au. See countries.xml for all code names. * @return Country that has phone code as @param code. * or returns null if no country matches given code. */ static Country getByNameCodeFromAllCountries(Context context, String nameCode) { List<Country> countries = CountryUtils.getAllCountries(context); for (Country country : countries) { if (country.getIso().equalsIgnoreCase(nameCode)) { return country; } } return null; } static List<String> getCountryIsoByTimeZone(Context context, String timeZoneId) { Map<String, List<String>> timeZoneAndCountryIsos = getTimeZoneAndCountryISOs(context); return timeZoneAndCountryIsos.get(timeZoneId); } /** * Return list of Map for timezone and iso country. * @param context Caller context * @return List of timezone and country. */ private static Map<String, List<String>> getTimeZoneAndCountryISOs(Context context) { if (timeZoneAndCountryISOs != null && !timeZoneAndCountryISOs.isEmpty()) { return timeZoneAndCountryISOs; } timeZoneAndCountryISOs = new HashMap<>(); // Read from raw InputStream inputStream = context.getResources().openRawResource(R.raw.zone1970); BufferedReader buf = new BufferedReader(new InputStreamReader(inputStream)); String lineJustFetched; String[] wordsArray; try { while (true) { lineJustFetched = buf.readLine(); if (lineJustFetched == null) { break; } else { wordsArray = lineJustFetched.split("\t"); // Ignore line which have # as the first character. if(!lineJustFetched.substring(0,1).contains(" if (wordsArray.length >= 3) { // First word is country code or list of country code separate by comma List<String> isos = new ArrayList<>(); Collections.addAll(isos, wordsArray[0].split(",")); // Third word in wordsArray is timezone. timeZoneAndCountryISOs.put(wordsArray[2], isos); } } } } } catch (IOException e) { e.printStackTrace(); } return timeZoneAndCountryISOs; } }
package io.fabianterhorst.isometric; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Shape { private List<Path> paths; public Shape() { this.paths = new ArrayList<>(); } public Shape(List<Path> paths) { this.paths = paths; } public void push(Path path) { this.paths.add(path); } public void push(List<Path> paths) { this.paths.addAll(paths); } public List<Path> getPaths() { return paths; } public Shape translate(double dx, double dy, double dz) { List<Path> paths = new ArrayList<>(); for (Path path : this.paths) { paths.add(path.translate(dx, dy, dz)); } return new Shape(paths); } public Shape rotateX(Point origin, double angle) { List<Path> paths = new ArrayList<>(); for (Path path : this.paths) { paths.add(path.rotateX(origin, angle)); } return new Shape(paths); } public Shape rotateY(Point origin, double angle) { List<Path> paths = new ArrayList<>(); for (Path path : this.paths) { paths.add(path.rotateY(origin, angle)); } return new Shape(paths); } public Shape rotateZ(Point origin, double angle) { List<Path> paths = new ArrayList<>(); for (Path path : this.paths) { paths.add(path.rotateZ(origin, angle)); } return new Shape(paths); } public Shape scale(Point origin, Double dx, Double dy, Double dz) { List<Path> paths = new ArrayList<>(); for (Path path : this.paths) { paths.add(path.scale(origin, dx, dy, dz)); } return new Shape(paths); } public void scalePaths(Point origin, Double dx, Double dy, Double dz) { for (int i = 0, length = paths.size();i < length;i++) { paths.set(i, paths.get(i).scale(origin, dx, dy, dz)); } } public void translatePaths(double dx, double dy, double dz) { for (int i = 0, length = paths.size();i < length;i++) { paths.set(i, paths.get(i).translate(dx, dy, dz)); } } /** * Sort the list of faces by distance then map the entries, returning * only the path and not the added "further point" from earlier. */ public List<Path> orderedPaths() { Collections.sort(this.paths, new Comparator<Path>() { @Override public int compare(Path pathA, Path pathB) { return Double.compare(pathB.depth(), pathA.depth()); } }); return this.paths; } public static Shape extrude(Path path, @Nullable Double height) { height = height != null ? height : 1; Path topPath = path.translate(0, 0, height); int i; int length = path.points.size(); Shape shape = new Shape(); /* Push the top and bottom faces, top face must be oriented correctly */ shape.push(path.reverse()); shape.push(topPath); /* Push each side face */ for (i = 0; i < length; i++) { List<Point> points = new ArrayList<>(); points.add(topPath.points.get(i)); points.add(path.points.get(i)); points.add(path.points.get((i + 1) % length)); points.add(topPath.points.get((i + 1) % length)); shape.push(new Path(points)); } return shape; } }
package org.andnav.osm; import org.andnav.osm.util.GeoPoint; import org.andnav.osm.util.constants.OpenStreetMapConstants; import org.andnav.osm.views.OpenStreetMapView; import org.andnav.osm.views.overlay.MyLocationOverlay; import org.andnav.osm.views.util.OpenStreetMapRendererInfo; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.location.Location; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SubMenu; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; /** * Default map view activity. * @author Manuel Stahl * */ public class OpenStreetMap extends Activity implements OpenStreetMapConstants { // Constants private static final int MENU_MY_LOCATION = Menu.FIRST; private static final int MENU_MAP_MODE = MENU_MY_LOCATION + 1; private static final int MENU_ABOUT = MENU_MAP_MODE + 1; private static final int DIALOG_ABOUT_ID = 1; // Fields private SharedPreferences mPrefs; private OpenStreetMapView mOsmv; private MyLocationOverlay mLocationOverlay; // Constructors /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); final RelativeLayout rl = new RelativeLayout(this); this.mOsmv = new OpenStreetMapView(this, OpenStreetMapRendererInfo.values()[mPrefs.getInt(PREFS_RENDERER, OpenStreetMapRendererInfo.MAPNIK.ordinal())]); this.mLocationOverlay = new MyLocationOverlay(this.getBaseContext(), this.mOsmv); this.mOsmv.setBuiltInZoomControls(true); this.mOsmv.getOverlays().add(this.mLocationOverlay); rl.addView(this.mOsmv, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); this.setContentView(rl); mOsmv.getController().setZoom(mPrefs.getInt(PREFS_ZOOM_LEVEL, 1)); mOsmv.scrollTo(mPrefs.getInt(PREFS_SCROLL_X, 0), mPrefs.getInt(PREFS_SCROLL_Y, 0)); if(mPrefs.getBoolean(PREFS_SHOW_LOCATION, false)) this.mLocationOverlay.enableMyLocation(); this.mLocationOverlay.followLocation(mPrefs.getBoolean(PREFS_FOLLOW_LOCATION, true)); } @Override protected void onPause() { this.mLocationOverlay.disableMyLocation(); SharedPreferences.Editor edit = mPrefs.edit(); edit.putInt(PREFS_RENDERER, mOsmv.getRenderer().ordinal()); edit.putInt(PREFS_SCROLL_X, mOsmv.getScrollX()); edit.putInt(PREFS_SCROLL_Y, mOsmv.getScrollY()); edit.putInt(PREFS_ZOOM_LEVEL, mOsmv.getZoomLevel()); edit.putBoolean(PREFS_SHOW_LOCATION, mLocationOverlay.isMyLocationEnabled()); edit.putBoolean(PREFS_FOLLOW_LOCATION, mLocationOverlay.isLocationFollowEnabled()); edit.commit(); super.onPause(); } @Override protected void onResume() { super.onResume(); mOsmv.setRenderer(OpenStreetMapRendererInfo.values()[mPrefs.getInt(PREFS_RENDERER, OpenStreetMapRendererInfo.MAPNIK.ordinal())]); if(mPrefs.getBoolean(PREFS_SHOW_LOCATION, false)) this.mLocationOverlay.enableMyLocation(); } @Override public boolean onCreateOptionsMenu(final Menu pMenu) { pMenu.add(0, MENU_MY_LOCATION, Menu.NONE, R.string.my_location).setIcon(android.R.drawable.ic_menu_mylocation); { int id = 1000; final SubMenu mapMenu = pMenu.addSubMenu(0, MENU_MAP_MODE, Menu.NONE, R.string.map_mode).setIcon( android.R.drawable.ic_menu_mapmode); for (OpenStreetMapRendererInfo renderer : OpenStreetMapRendererInfo .values()) { mapMenu.add(MENU_MAP_MODE, id++, Menu.NONE, getString(renderer.NAME)); } mapMenu.setGroupCheckable(MENU_MAP_MODE, true, true); } pMenu.add(0, MENU_ABOUT, Menu.NONE, R.string.about).setIcon(android.R.drawable.ic_menu_info_details); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { int id = mOsmv.getRenderer().ordinal(); menu.findItem(1000 + id).setChecked(true); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch(item.getItemId()) { case MENU_MY_LOCATION: this.mLocationOverlay.followLocation(true); this.mLocationOverlay.enableMyLocation(); Location lastFix = this.mLocationOverlay.getLastFix(); if (lastFix != null) this.mOsmv.setMapCenter(new GeoPoint(lastFix)); return true; case MENU_MAP_MODE: this.mOsmv.invalidate(); return true; case MENU_ABOUT: showDialog(DIALOG_ABOUT_ID); return true; default: // Map mode submenu items this.mOsmv.setRenderer(OpenStreetMapRendererInfo.values()[item.getItemId() - 1000]); } return false; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch (id) { case DIALOG_ABOUT_ID: return new AlertDialog.Builder(OpenStreetMap.this) .setIcon(R.drawable.icon) .setTitle(R.string.app_name) .setMessage(R.string.about_message) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {} }).create(); default: dialog = null; break; } return dialog; } // Getter & Setter // Methods from SuperClass/Interfaces @Override public boolean onTrackballEvent(MotionEvent event) { return this.mOsmv.onTrackballEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE) this.mLocationOverlay.followLocation(false); return super.onTouchEvent(event); } // Methods // Inner and Anonymous Classes }
package edu.mit.streamjit.test.sanity; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider; import edu.mit.streamjit.api.DuplicateSplitter; import edu.mit.streamjit.api.Identity; import edu.mit.streamjit.api.Input; import edu.mit.streamjit.api.Joiner; import edu.mit.streamjit.api.RoundrobinJoiner; import edu.mit.streamjit.api.RoundrobinSplitter; import edu.mit.streamjit.api.Splitjoin; import edu.mit.streamjit.api.Splitter; import edu.mit.streamjit.api.WeightedRoundrobinJoiner; import edu.mit.streamjit.api.WeightedRoundrobinSplitter; import edu.mit.streamjit.impl.blob.Buffer; import edu.mit.streamjit.impl.common.InputBufferFactory; import edu.mit.streamjit.test.SuppliedBenchmark; import edu.mit.streamjit.test.Benchmark; import edu.mit.streamjit.test.Benchmark.Dataset; import edu.mit.streamjit.test.BenchmarkProvider; import edu.mit.streamjit.test.Datasets; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Queue; /** * Tests that splitjoins using the built-in splitters order their elements * properly. * * TODO: we run the simulator even if we aren't going to run any of the * benchmarks. We'll need to do that lazily at some point. * * TODO: the splitjoin simulator should be refactored into a splitter simulator * and joiner simulator, so we can plug any of the splitters with any of the * joiners. Right now we have a copy for the duplicate splitter. * @see SplitjoinComputeSanity * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 8/20/2013 */ @ServiceProvider(BenchmarkProvider.class) public final class SplitjoinOrderSanity implements BenchmarkProvider { @Override public Iterator<Benchmark> iterator() { Benchmark[] benchmarks = { rr_rr(7, 1, 1), rr_rr(7, 5, 5), rr_rr(7, 5, 3), rr_rr(7, 3, 5), wrr_rr(1, new int[]{1}, 1), wrr_rr(7, new int[]{1, 1, 1, 1, 1, 1, 1}, 1), wrr_rr(7, new int[]{5, 5, 5, 5, 5, 5, 5}, 5), rr_wrr(1, 1, new int[]{1}), rr_wrr(7, 1, new int[]{1, 1, 1, 1, 1, 1, 1}), rr_wrr(7, 5, new int[]{5, 5, 5, 5, 5, 5, 5}), wrr_wrr(1, new int[]{1}, new int[]{1}), wrr_wrr(7, new int[]{1, 1, 1, 1, 1, 1, 1}, new int[]{1, 1, 1, 1, 1, 1, 1}), wrr_wrr(7, new int[]{5, 5, 5, 5, 5, 5, 5}, new int[]{5, 5, 5, 5, 5, 5, 5}), wrr_wrr(7, new int[]{1, 2, 3, 4, 3, 2, 1}, new int[]{1, 2, 3, 4, 3, 2, 1}), dup_rr(7, 1), dup_rr(7, 7), dup_wrr(1, new int[]{1}), dup_wrr(7, new int[]{1, 1, 1, 1, 1, 1, 1}), dup_wrr(7, new int[]{5, 5, 5, 5, 5, 5, 5}), }; return Arrays.asList(benchmarks).iterator(); } private static Benchmark rr_rr(int width, int splitRate, int joinRate) { String name = String.format("RR(%d) x %dw x RR(%d)", splitRate, width, joinRate); return new SuppliedBenchmark(name, new SplitjoinSupplier(width, new RoundrobinSplitterSupplier(splitRate), new RoundrobinJoinerSupplier(joinRate)), simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRate, joinRate)); } private static Benchmark wrr_rr(int width, int[] splitRates, int joinRate) { String name = String.format("WRR(%s) x %dw x RR(%d)", Arrays.toString(splitRates), width, joinRate); return new SuppliedBenchmark(name, new SplitjoinSupplier(width, new WeightedRoundrobinSplitterSupplier(splitRates), new RoundrobinJoinerSupplier(joinRate)), simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRates, joinRate)); } private static Benchmark rr_wrr(int width, int splitRate, int[] joinRates) { String name = String.format("RR(%d) x %dw x WRR(%s)", splitRate, width, Arrays.toString(joinRates)); return new SuppliedBenchmark(name, new SplitjoinSupplier(width, new RoundrobinSplitterSupplier(splitRate), new WeightedRoundrobinJoinerSupplier(joinRates)), simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRate, joinRates)); } private static Benchmark wrr_wrr(int width, int[] splitRates, int[] joinRates) { String name = String.format("WRR(%s) x %dw x WRR(%s)", Arrays.toString(splitRates), width, Arrays.toString(joinRates)); return new SuppliedBenchmark(name, new SplitjoinSupplier(width, new WeightedRoundrobinSplitterSupplier(splitRates), new WeightedRoundrobinJoinerSupplier(joinRates)), simulateRoundrobin(Datasets.allIntsInRange(0, 1_000_000), width, splitRates, joinRates)); } private static Benchmark dup_rr(int width, int joinRate) { String name = String.format("dup x %dw x RR(%d)", width, joinRate); Dataset dataset = Datasets.allIntsInRange(0, 1_000_000); dataset = dataset.withInput(DuplicateSimulator.create(dataset.input(), width, joinRate).get()); return new SuppliedBenchmark(name, new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new RoundrobinJoinerSupplier(joinRate)), dataset); } private static Benchmark dup_wrr(int width, int[] joinRates) { String name = String.format("dup x %dw x WRR(%s)", width, Arrays.toString(joinRates)); Dataset dataset = Datasets.allIntsInRange(0, 1_000_000); dataset = dataset.withInput(DuplicateSimulator.create(dataset.input(), width, joinRates).get()); return new SuppliedBenchmark(name, new SplitjoinSupplier(width, new DuplicateSplitterSupplier(), new WeightedRoundrobinJoinerSupplier(joinRates)), dataset); } private static final class SplitjoinSupplier implements Supplier<Splitjoin<Integer, Integer>> { private final int width; private final Supplier<? extends Splitter<Integer, Integer>> splitter; private final Supplier<? extends Joiner<Integer, Integer>> joiner; private SplitjoinSupplier(int width, Supplier<? extends Splitter<Integer, Integer>> splitter, Supplier<? extends Joiner<Integer, Integer>> joiner) { this.width = width; this.splitter = splitter; this.joiner = joiner; } @Override public Splitjoin<Integer, Integer> get() { ImmutableList.Builder<Identity<Integer>> builder = ImmutableList.builder(); //Can't use Collections.nCopies because we need distinct filters. for (int i = 0; i < width; ++i) builder.add(new Identity<Integer>()); return new Splitjoin<>(splitter.get(), joiner.get(), builder.build()); } } //I'd like to use ConstructorSupplier here, but the generics won't work //because e.g. RoundrobinSplitter.class is a raw type. private static final class RoundrobinSplitterSupplier implements Supplier<Splitter<Integer, Integer>> { private final int rate; private RoundrobinSplitterSupplier(int rate) { this.rate = rate; } @Override public Splitter<Integer, Integer> get() { return new RoundrobinSplitter<>(rate); } } private static final class RoundrobinJoinerSupplier implements Supplier<Joiner<Integer, Integer>> { private final int rate; private RoundrobinJoinerSupplier(int rate) { this.rate = rate; } @Override public Joiner<Integer, Integer> get() { return new RoundrobinJoiner<>(rate); } } private static final class WeightedRoundrobinSplitterSupplier implements Supplier<Splitter<Integer, Integer>> { private final int[] rates; private WeightedRoundrobinSplitterSupplier(int[] rates) { this.rates = rates; } @Override public Splitter<Integer, Integer> get() { return new WeightedRoundrobinSplitter<>(rates); } } private static final class WeightedRoundrobinJoinerSupplier implements Supplier<Joiner<Integer, Integer>> { private final int[] rates; private WeightedRoundrobinJoinerSupplier(int[] rates) { this.rates = rates; } @Override public Joiner<Integer, Integer> get() { return new WeightedRoundrobinJoiner<>(rates); } } private static final class DuplicateSplitterSupplier implements Supplier<Splitter<Integer, Integer>> { @Override public Splitter<Integer, Integer> get() { return new DuplicateSplitter<>(); } } /** * Simulates a roundrobin splitjoin, returning a Dataset with reference * output. */ private static Dataset simulateRoundrobin(Dataset dataset, int width, int splitRate, int joinRate) { int[] splitRates = new int[width], joinRates = new int[width]; Arrays.fill(splitRates, splitRate); Arrays.fill(joinRates, joinRate); return simulateRoundrobin(dataset, width, splitRates, joinRates); } private static Dataset simulateRoundrobin(Dataset dataset, int width, int[] splitRates, int joinRate) { int[] joinRates = new int[width]; Arrays.fill(joinRates, joinRate); return simulateRoundrobin(dataset, width, splitRates, joinRates); } private static Dataset simulateRoundrobin(Dataset dataset, int width, int splitRate, int[] joinRates) { int[] splitRates = new int[width]; Arrays.fill(splitRates, splitRate); return simulateRoundrobin(dataset, width, splitRates, joinRates); } /** * Simulates a weighted roundrobin splitjoin, returning a Dataset with * reference output. */ private static Dataset simulateRoundrobin(Dataset dataset, int width, int[] splitRates, int[] joinRates) { List<Queue<Object>> bins = new ArrayList<>(width); for (int i = 0; i < width; ++i) bins.add(new ArrayDeque<>()); int splitReq = 0; for (int i : splitRates) splitReq += i; Buffer buffer = InputBufferFactory.unwrap(dataset.input()).createReadableBuffer(splitReq); while (buffer.size() >= splitReq) for (int i = 0; i < bins.size(); ++i) for (int j = 0; j < splitRates[i]; ++j) bins.get(i).add(buffer.read()); List<Object> output = new ArrayList<>(); while (ready(bins, joinRates)) { for (int i = 0; i < bins.size(); ++i) for (int j = 0; j < joinRates[i]; ++j) output.add(bins.get(i).remove()); } return dataset.withOutput(Input.fromIterable(output)); } private static final class DuplicateSimulator<T> implements Supplier<Input<T>> { private final Input<T> input; private final int width; private final int[] joinRates; public static <T> DuplicateSimulator<T> create(Input<T> input, int width, int joinRate) { int[] joinRates = new int[width]; Arrays.fill(joinRates, joinRate); return create(input, width, joinRates); } public static <T> DuplicateSimulator<T> create(Input<T> input, int width, int[] joinRates) { return new DuplicateSimulator<>(input, width, joinRates); } private DuplicateSimulator(Input<T> input, int width, int[] joinRates) { this.input = input; this.width = width; this.joinRates = joinRates; } @Override @SuppressWarnings("unchecked") public Input<T> get() { List<Queue<T>> bins = new ArrayList<>(width); for (int i = 0; i < width; ++i) bins.add(new ArrayDeque<T>()); Buffer buffer = InputBufferFactory.unwrap(input).createReadableBuffer(42); while (buffer.size() > 0) { Object o = buffer.read(); for (int i = 0; i < bins.size(); ++i) bins.get(i).add((T)o); } List<T> output = new ArrayList<>(); while (ready(bins, joinRates)) { for (int i = 0; i < bins.size(); ++i) for (int j = 0; j < joinRates[i]; ++j) output.add(bins.get(i).remove()); } return Input.fromIterable(output); } } private static <T> boolean ready(List<Queue<T>> bins, int[] joinRates) { for (int i = 0; i < bins.size(); ++i) if (bins.get(i).size() < joinRates[i]) return false; return true; } }
package org.nutz.dao.entity.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * * * <b></b> * * @author pangwu86(pangwu86@gmail.com) */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) @Documented public @interface Comment { String value() default ""; }
package edu.utdallas.robotchess.pathplanning; import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Stack; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import edu.utdallas.robotchess.engine.Move; public class MotionPlanner { final int INF = 1000; final int REGULAR_SQUARE_COUNT = 64; final int REGULAR_ROW_SIZE = 8; final int REGULAR_COLUMN_SIZE = 8; @SuppressWarnings("unused") private final static Logger log = Logger.getLogger(MotionPlanner.class); int boardRows; int boardColumns; public MotionPlanner(int boardRows, int boardColumns) { PropertyConfigurator.configure("log/log4j.properties"); this.boardRows = boardRows; this.boardColumns = boardColumns; } public ArrayList<Path> plan(int currentLocations[], int desiredLocations[]) { ArrayList<Path> plan = new ArrayList<>(); boolean occupancyGrid[] = fillOccupancyGrid(currentLocations); ArrayList<Move> movesNeeded = generateMoves(currentLocations, desiredLocations); // for now, let's not handle any more than single move plans if (movesNeeded.size() > 1) return plan; for (Move move : movesNeeded) { Path path = new Path(move.pieceID, move.origin); ArrayList<Integer> squareSequence = dijkstra(occupancyGrid, move.origin, move.destination); path.setSquareSequence(squareSequence); plan.add(path); } return plan; } private boolean[] fillOccupancyGrid(int currentLocations[]) { boolean occupancyGrid[] = new boolean[REGULAR_SQUARE_COUNT]; for (int i = 0; i < occupancyGrid.length; i++) occupancyGrid[i] = false; for (int i = 0; i < currentLocations.length; i++) if (currentLocations[i] != -1) occupancyGrid[currentLocations[i]] = true; return occupancyGrid; } private ArrayList<Move> generateMoves(int currentLocations[], int desiredLocations[]) { ArrayList<Move> moves = new ArrayList<>(); for (int i = 0; i < currentLocations.length; i++) if (currentLocations[i] != desiredLocations[i]) moves.add(new Move(i, currentLocations[i], desiredLocations[i])); return moves; } private ArrayList<Edge> computeEdges(boolean[] occupancyGrid, int vertex) { final int LATERAL_WEIGHT = 2; final int DIAGONAL_WEIGHT = 50; ArrayList<Edge> edges = new ArrayList<>(); // check north neighbor if (vertex > REGULAR_ROW_SIZE) edges.add(new Edge(vertex, vertex - REGULAR_ROW_SIZE, LATERAL_WEIGHT)); // check northeast neighbor if (vertex > REGULAR_ROW_SIZE && vertex % REGULAR_ROW_SIZE < boardColumns - 1) edges.add(new Edge(vertex, vertex - REGULAR_ROW_SIZE + 1, DIAGONAL_WEIGHT)); // check east neighbor if (vertex % REGULAR_ROW_SIZE < boardColumns - 1) edges.add(new Edge(vertex, vertex + 1, LATERAL_WEIGHT)); // check southeast neighbor if (vertex < REGULAR_COLUMN_SIZE * (boardRows - 1) && vertex % REGULAR_ROW_SIZE < boardColumns - 1) edges.add(new Edge(vertex, vertex + REGULAR_ROW_SIZE + 1, DIAGONAL_WEIGHT)); // check south neighbor if (vertex < REGULAR_COLUMN_SIZE * (boardRows - 1)) edges.add(new Edge(vertex, vertex + REGULAR_ROW_SIZE, LATERAL_WEIGHT)); // check southwest neighbor if (vertex < REGULAR_COLUMN_SIZE * (boardRows - 1) && vertex % REGULAR_ROW_SIZE != 0) edges.add(new Edge(vertex, vertex + REGULAR_ROW_SIZE - 1, DIAGONAL_WEIGHT)); // check west neighbor if (vertex % REGULAR_ROW_SIZE != 0) edges.add(new Edge(vertex, vertex - 1, LATERAL_WEIGHT)); // check northwest neighbor if (vertex > REGULAR_ROW_SIZE && vertex % REGULAR_ROW_SIZE != 0) edges.add(new Edge(vertex, vertex - REGULAR_ROW_SIZE - 1, DIAGONAL_WEIGHT)); // we can't move to a square that is occupied by another piece // remove edges whose destinations are occupied for (int i = 0; i < edges.size(); i++) { Edge testEdge = edges.get(i); if (occupancyGrid[testEdge.destination]) edges.remove(i } return edges; } private ArrayList<Integer> dijkstra(boolean[] occupancyGrid, int origin, int destination) { Vertex vertices[] = new Vertex[REGULAR_SQUARE_COUNT]; PriorityQueue<Vertex> queue = new PriorityQueue<>(boardRows * boardColumns, new VertexComparator()); enqueueVertices(vertices, queue, origin); updateDistances(occupancyGrid, vertices, queue); ArrayList<Integer> path = generatePath(vertices, destination); return path; } private void enqueueVertices(Vertex vertices[], PriorityQueue<Vertex> queue, int origin) { for (int i = 0; i < vertices.length; i++) { if (i == origin) vertices[i] = new Vertex(i, 0); else vertices[i] = new Vertex(i, INF); queue.add(vertices[i]); } } private void updateDistances(boolean[] occupancyGrid, Vertex vertices[], PriorityQueue<Vertex> queue) { while (queue.size() > 0) { Vertex u = queue.poll(); ArrayList<Edge> edges = computeEdges(occupancyGrid, u.id); for (Edge e : edges) { Vertex v = vertices[e.destination]; if (v.distance > u.distance + e.weight) { queue.remove(v); v.distance = u.distance + e.weight; v.predecessor = u; queue.add(v); } } } } private ArrayList<Integer> generatePath(Vertex vertices[], int destination) { Stack<Vertex> stack = new Stack<>(); Vertex u = vertices[destination]; while (u.predecessor != null) { stack.push(u); u = u.predecessor; } ArrayList<Integer> path = new ArrayList<>(); while (!stack.empty()) { u = stack.pop(); path.add(u.id); } return path; } } class Vertex { int distance; int id; Vertex predecessor; Vertex(int id, int distance) { this.distance = distance; this.id = id; predecessor = null; } @Override public String toString() { String str = new String(); str = String.format("Vertex ID: %d. Distance: %d.", id, distance); return str; } } class Edge { int origin; int destination; int weight; Edge(int origin, int destination, int weight) { this.origin = origin; this.destination = destination; this.weight = weight; } } class VertexComparator implements Comparator<Vertex> { @Override public int compare(Vertex x, Vertex y) { if (x.distance < y.distance) return -1; if (x.distance > y.distance) return 1; return 0; } }
package org.reprap.comms.snap; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.UnsupportedCommOperationException; import org.reprap.Device; import org.reprap.Preferences; import org.reprap.comms.Address; import org.reprap.comms.Communicator; import org.reprap.comms.IncomingContext; import org.reprap.comms.IncomingMessage; import org.reprap.comms.OutgoingMessage; public class SNAPCommunicator implements Communicator { private final static int ackTimeout = 300; private final static int messageTimeout = 300; private Address localAddress; private SerialPort port; private OutputStream writeStream; private InputStream readStream; //private ReceiveThread receiveThread = null; private boolean debugMode; private CommsLock lock = new CommsLock(); public SNAPCommunicator(String portName, int baudRate, Address localAddress) throws NoSuchPortException, PortInUseException, IOException, UnsupportedCommOperationException { this.localAddress = localAddress; System.out.println("Opening port "+portName); CommPortIdentifier commId = CommPortIdentifier.getPortIdentifier(portName); port = (SerialPort)commId.open(portName, 30000); // Workround for javax.comm bug. try { port.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (Exception e) { } port.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // End of workround try { port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); } catch (Exception e) { // Um, Linux USB ports don't do this. What can I do about it? } writeStream = port.getOutputStream(); readStream = port.getInputStream(); try { // Try to load debug setting from properties file debugMode = Preferences.loadGlobalBool("CommsDebug"); } catch (Exception ex) { // Fall back to non-debug mode if no setting is available debugMode = false; } } public void close() { if (port != null) port.close(); port = null; } private void dumpPacket(Device device, OutgoingMessage messageToSend) { byte [] binaryMessage = messageToSend.getBinary(); System.out.print(localAddress.toString()); System.out.print("->"); System.out.print(device.getAddress().toString()); System.out.print(": "); for(int i = 0; i < binaryMessage.length; i++) System.out.print(Integer.toHexString(binaryMessage[i]>=0?binaryMessage[i]:binaryMessage[i]+256) + " "); System.out.println(""); } public IncomingContext sendMessage(Device device, OutgoingMessage messageToSend) throws IOException { byte [] binaryMessage = messageToSend.getBinary(); SNAPPacket packet = new SNAPPacket((SNAPAddress)localAddress, (SNAPAddress)device.getAddress(), binaryMessage); for(;;) { if (debugMode) { System.out.print("TX "); dumpPacket(device, messageToSend); } sendRawMessage(packet); SNAPPacket ackPacket; try { ackPacket = receivePacket(ackTimeout); } catch (IOException ex) { // An error occurred during receive, so send and try again //if (debugMode) { System.out.println("Receive error, re-sending: " + ex.getMessage()); dumpPacket(device, messageToSend); continue; } if (ackPacket.isAck()) break; if (ackPacket.getSourceAddress().equals(localAddress)) { // Packet was from us, so assume no node present System.out.println("Device at address " + device.getAddress() + " not present"); throw new IOException("Device at address " + device.getAddress() + " not present"); } if (!ackPacket.isNak()) { System.out.println("Received data packet when expecting ACK"); } System.out.println("sendMessage error - retrying"); try { Thread.sleep(100); } catch (Exception e) { } } IncomingContext replyContext = messageToSend.getReplyContext(this, device); return replyContext; } private synchronized void sendRawMessage(SNAPPacket packet) throws IOException { // try{ // Thread.sleep(200); // } catch (Exception ex) // System.err.println("Comms sleep: " + ex.toString()); writeStream.write(packet.getRawData()); } private int readByte(long timeout) throws IOException { long t0 = System.currentTimeMillis(); int c = -1; // Sometimes javacomm seems to freak out and say something // timed out when it didn't, so double check and try again // if it really didn't time out for(;;) { c = readStream.read(); if (c != -1) return c; if (System.currentTimeMillis() - t0 >= timeout) return -1; try { // Just to avoid a deadly spin if something unexpected happens Thread.sleep(1); } catch (InterruptedException e) { } } } protected synchronized SNAPPacket receivePacket(long timeout) throws IOException { SNAPPacket packet = null; if (debugMode) System.out.print("RX "); try { port.enableReceiveTimeout(messageTimeout); } catch (UnsupportedCommOperationException e) { System.out.println("Read timeouts unsupported on this platform"); } for(;;) { int c = readByte(timeout); if (debugMode) System.out.print(Integer.toHexString(c) + " "); if (c == -1) throw new IOException("Timeout receiving byte"); if (packet == null) { if (c != 0x54) // Always wait for a sync byte before doing anything continue; packet = new SNAPPacket(); } if (packet.receiveByte((byte)c)) { // Packet is complete if (packet.validate()) { if (debugMode) System.out.println(""); return packet; } else { System.out.println("CRC error"); throw new IOException("CRC error"); } } } } public void receiveMessage(IncomingMessage message) throws IOException { receiveMessage(message, messageTimeout); } public void receiveMessage(IncomingMessage message, long timeout) throws IOException { // Here we collect one packet and notify the message // of its contents. The message will respond // to indicate if it wants the message. If not, // it will be discarded and we will wait for another // message. // Since this is a SNAP ring, we have to pass on // any packets that are not destined for us. // We will also only pass packets to the message if they are for // the local address. for(;;) { SNAPPacket packet = receivePacket(timeout); if (processPacket(message, packet)) return; } } private boolean processPacket(IncomingMessage message, SNAPPacket packet) throws IOException { // First ACK the message if (packet.isAck()) { System.out.println("Unexpected ACK received instead of message, not supported yet"); return false; } /// TODO send ACKs //sendRawMessage(packet.generateACK()); if (!packet.getDestinationAddress().equals(localAddress)) { // Not for us, so forward it on sendRawMessage(packet); return false; } else if (message.receiveData(packet.getPayload())) { // All received as expected return true; } else { // Not interested, wait for more System.out.println("Ignored and dropped packet"); return false; } } public Address getAddress() { return localAddress; } public void dispose() { close(); } public void lock() { lock.lock(); } public void unlock() { lock.unlock(); } // TODO make a background receiver thread. It can keep a pool of async receive contexts and // fire them off if anything matching arrives. // TODO Make a generic message receiver. Use reflection to get correct class. }
package org.jetbrains.yaml.meta.model; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import org.jetbrains.annotations.*; import org.jetbrains.yaml.psi.YAMLKeyValue; import javax.swing.*; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @SuppressWarnings("UnusedReturnValue") @ApiStatus.Internal public class Field { public enum Relation { SCALAR_VALUE, SEQUENCE_ITEM, OBJECT_CONTENTS } private final String myName; private final MetaTypeSupplier myMetaTypeSupplier; // must be accessed with getMainType() @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private YamlMetaType myMainType; private boolean myIsRequired; private boolean myEditable = true; private boolean myDeprecated = false; private boolean myAnyNameAllowed; private boolean myEmptyValueAllowed; private boolean myIsMany; private Relation myOverriddenDefaultRelation; private final Map<Relation, YamlMetaType> myPerRelationTypes = new HashMap<>(); /** * Used in {@link Field#Field(String, MetaTypeSupplier)}. * Invoked only once */ public interface MetaTypeSupplier { @NotNull YamlMetaType getMainType(); } public Field(@NonNls @NotNull String name, @NotNull YamlMetaType mainType) { this(name, () -> mainType); } /** * Used for late initialization of the field metatype. * Useful when the type isn't fully constructed at the moment of the field initialization (e.g. for cyclic dependencies) */ public Field(@NonNls @NotNull String name, @NotNull MetaTypeSupplier provider) { myName = name; myMetaTypeSupplier = provider; } @NotNull public Field withDefaultRelation(@NotNull Relation relation) { myOverriddenDefaultRelation = relation; return this; } public Field withRelationSpecificType(@NotNull Relation relation, @NotNull YamlMetaType specificType) { myPerRelationTypes.put(relation, specificType); return this; } @NotNull public Field withMultiplicityMany() { return withMultiplicityManyNotOne(true); } @NotNull public Field withMultiplicityManyNotOne(boolean manyNotOne) { myIsMany = manyNotOne; return this; } @Contract(pure = true) public boolean isMany() { return myIsMany; } @NotNull public Field setRequired() { myIsRequired = true; return this; } @NotNull public Field setDeprecated() { myDeprecated = true; return this; } /** * Marks the field non-editable. This is useful when the file content is not created initially by user, but rather machine-generated, * and contains fields not intended for editing, but still valid in terms of the data schema. * (This is very common for Kubernetes resource files, for example.) * Non-editable fields aren't included in completion lists. Also there is an inspection for highlighting such data. */ @NotNull public Field setNonEditable() { myEditable = false; return this; } @Contract(pure = true) public final boolean isRequired() { return myIsRequired; } /** * Returns whether the field is editable. True by default * * @see #setNonEditable() */ @Contract(pure = true) public final boolean isEditable() { return myEditable; } /** * Returns whether the field is deprecated. False by default * * @see #setDeprecated() */ @Contract(pure = true) public boolean isDeprecated() { return myDeprecated; } @Contract(pure = true) public final String getName() { return myName; } @Contract(pure = true) @NotNull public YamlMetaType getType(@NotNull Relation relation) { return myPerRelationTypes.getOrDefault(relation, getMainType()); } @Contract(pure = true) @NotNull public YamlMetaType getDefaultType() { return getType(getDefaultRelation()); } /** * Returns the default relation between the field and its value. For most normal fields it can be computed based on type and multiplicity * but for polymorphic fields the main relation should be assigned explicitly. */ @NotNull public Relation getDefaultRelation() { if (myOverriddenDefaultRelation != null) { return myOverriddenDefaultRelation; } if (myIsMany) { return Relation.SEQUENCE_ITEM; } return getMainType() instanceof YamlScalarType ? Relation.SCALAR_VALUE : Relation.OBJECT_CONTENTS; } @NotNull public Field withEmptyValueAllowed(boolean allow) { myEmptyValueAllowed = allow; return this; } @NotNull public final Field withAnyName() { return withAnyName(true); } @NotNull public Field withAnyName(boolean allowAnyName) { myAnyNameAllowed = allowAnyName; return this; } public final boolean isAnyNameAllowed() { return myAnyNameAllowed; } public final boolean isEmptyValueAllowed() { return myEmptyValueAllowed; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("[").append(getName()).append("]@"); result.append(Integer.toHexString(hashCode())); result.append(" : "); result.append(getMainType().getTypeName()); List<String> nonDefaultTypes = myPerRelationTypes.entrySet().stream() .filter(e -> e.getValue() == getMainType()) .map(e -> e.getKey() + ":" + e.getValue()) .collect(Collectors.toList()); if (!nonDefaultTypes.isEmpty()) { result.append(nonDefaultTypes); } return result.toString(); } @NotNull public List<LookupElementBuilder> getKeyLookups(@NotNull YamlMetaType ownerClass, @NotNull PsiElement insertedScalar) { if (isAnyNameAllowed()) { return Collections.emptyList(); } LookupElementBuilder lookup = LookupElementBuilder .create(new TypeFieldPair(ownerClass, this), getName()) .withTypeText(getMainType().getDisplayName(), true) .withIcon(getLookupIcon()) .withStrikeoutness(isDeprecated()); if (isRequired()) { lookup = lookup.bold(); } return Collections.singletonList(lookup); } @Nullable public PsiReference getReferenceFromKey(@NotNull YAMLKeyValue keyValue) { return null; } public boolean hasRelationSpecificType(@NotNull Relation relation) { return relation == getDefaultRelation() || myPerRelationTypes.containsKey(relation); } @Nullable public Icon getLookupIcon() { return myIsMany ? AllIcons.Json.Array : getMainType().getIcon(); } @NotNull private YamlMetaType getMainType() { if(myMainType != null) return myMainType; synchronized (myMetaTypeSupplier) { if(myMainType == null) { try { myMainType = myMetaTypeSupplier.getMainType(); } catch (Exception e) { throw new RuntimeException("Supplier failed to return a metatype for field: " + this, e); } } return myMainType; } } }
package com.github.lgooddatepicker.demo; import com.github.lgooddatepicker.calendarpanel.CalendarPanel; import com.github.lgooddatepicker.zinternaltools.DemoPanel; import com.github.lgooddatepicker.datepicker.DatePicker; import javax.swing.JButton; import javax.swing.JFrame; import java.awt.event.ActionEvent; import java.util.Locale; import java.awt.Color; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.GridBagConstraints; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JPanel; import com.github.lgooddatepicker.datepicker.DatePickerSettings; import com.github.lgooddatepicker.optionalusertools.DateChangeListener; import com.github.lgooddatepicker.optionalusertools.PickerUtilities; import com.github.lgooddatepicker.zinternaltools.DateChangeEvent; import com.github.lgooddatepicker.zinternaltools.InternalUtilities; import com.github.lgooddatepicker.zinternaltools.WrapLayout; import com.github.lgooddatepicker.zinternaltools.CalendarSelectionEvent; import com.github.lgooddatepicker.zinternaltools.DateTimeChangeEvent; import com.github.lgooddatepicker.zinternaltools.TimeChangeEvent; import com.github.lgooddatepicker.optionalusertools.DateVetoPolicy; import com.github.lgooddatepicker.optionalusertools.DateHighlightPolicy; import com.github.lgooddatepicker.optionalusertools.TimeChangeListener; import com.github.lgooddatepicker.optionalusertools.TimeVetoPolicy; import com.github.lgooddatepicker.datetimepicker.DateTimePicker; import com.github.lgooddatepicker.optionalusertools.DateTimeChangeListener; import com.github.lgooddatepicker.timepicker.TimePicker; import com.github.lgooddatepicker.timepicker.TimePickerSettings; import com.github.lgooddatepicker.timepicker.TimePickerSettings.TimeIncrement; import com.privatejgoodies.forms.factories.CC; import javax.swing.border.LineBorder; import com.github.lgooddatepicker.optionalusertools.CalendarSelectionListener; import com.github.lgooddatepicker.zinternaltools.HighlightInformation; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionListener; import java.io.InputStream; import java.net.URL; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.format.DateTimeFormatter; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; /** * FullDemo, This class contains a demonstration of various features of the DatePicker library * components. * * Optional features: Most of the features shown in this demo are optional. The simplest usage only * requires creating a date picker instance and adding it to a panel or window. The selected date * can then be retrieved with the function datePicker.getDate(). For a simpler demo, see * "BasicDemo.java". * * Running the demo: This is an executable demonstration. To run the demo, click "run file" (or the * equivalent command) for the class in your IDE. */ public class FullDemo { // This holds our main frame. static JFrame frame; // This holds our display panel. static DemoPanel panel; // These hold date pickers. static DatePicker datePicker; static DatePicker datePicker1; static DatePicker datePicker2; // These hold time pickers. static TimePicker timePicker; static TimePicker timePicker1; static TimePicker timePicker2; // These hold DateTimePickers. static DateTimePicker dateTimePicker1; static DateTimePicker dateTimePicker2; static DateTimePicker dateTimePicker3; static DateTimePicker dateTimePicker4; static DateTimePicker dateTimePicker5; // Date pickers are placed on the rows at a set interval. static final int rowMultiplier = 4; /** * main, The application entry point. */ public static void main(String[] args) { // If desired, set a swing look and feel here. try { /* // Set a specific look and feel. for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } // Set a random look and feel. LookAndFeelInfo[] installedLooks = UIManager.getInstalledLookAndFeels(); int lookIndex = (int) (Math.random() * installedLooks.length); UIManager.setLookAndFeel(installedLooks[lookIndex].getClassName()); System.out.println(installedLooks[lookIndex].getClassName().toString()); */ } catch (Exception e) { } // Create a frame, a panel, and our demo buttons. frame = new JFrame(); frame.setTitle("LGoodDatePicker Demo " + InternalUtilities.getProjectVersionString()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new DemoPanel(); frame.getContentPane().add(panel); createDemoButtons(); // This section creates DatePickers, with various features. // Create a settings variable for repeated use. DatePickerSettings dateSettings; int row = rowMultiplier; // Create a date picker: With default settings datePicker1 = new DatePicker(); panel.panel1.add(datePicker1, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 1, Default Settings:"); // Create a date picker: With highlight policy. dateSettings = new DatePickerSettings(); datePicker2 = new DatePicker(dateSettings); dateSettings.highlightPolicy = new SampleHighlightPolicy(); panel.panel1.add(datePicker2, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 2, Highlight Policy:"); // Create a date picker: With veto policy. // Note: Veto policies can only be set after constructing the date picker. dateSettings = new DatePickerSettings(); datePicker = new DatePicker(dateSettings); dateSettings.setVetoPolicy(new SampleDateVetoPolicy()); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 3, Veto Policy:"); // Create a date picker: With both policies. // Note: Veto policies can only be set after constructing the date picker. dateSettings = new DatePickerSettings(); datePicker = new DatePicker(dateSettings); dateSettings.highlightPolicy = new SampleHighlightPolicy(); dateSettings.setVetoPolicy(new SampleDateVetoPolicy()); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 4, Both Policies:"); // Create a date picker: Change calendar size. dateSettings = new DatePickerSettings(); dateSettings.sizeDatePanelMinimumHeight *= 1.6; dateSettings.sizeDatePanelMinimumWidth *= 1.6; datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 5, Change Calendar Size:"); // Create a date picker: Custom color. dateSettings = new DatePickerSettings(); dateSettings.colorBackgroundCalendarPanel = Color.green; dateSettings.colorBackgroundWeekdayLabels = Color.orange; dateSettings.colorBackgroundMonthAndYear = Color.yellow; dateSettings.colorBackgroundTodayAndClear = Color.yellow; dateSettings.colorBackgroundNavigateYearMonthButtons = Color.cyan; datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 6, Change Colors:"); // Create a date picker: Custom button icon. // You can replace the example image with any image file that is desired. // See also: JButton.setPressedIcon() and JButton.setDisabledIcon(). // Get the example image icon. URL dateImageURL = FullDemo.class.getResource("/images/datepickerbutton1.png"); Image dateExampleImage = Toolkit.getDefaultToolkit().getImage(dateImageURL); ImageIcon dateExampleIcon = new ImageIcon(dateExampleImage); // Create the date picker, and apply the image icon. dateSettings = new DatePickerSettings(); dateSettings.setInitialDateToToday(); datePicker = new DatePicker(dateSettings); JButton datePickerButton = datePicker.getComponentToggleCalendarButton(); datePickerButton.setText(""); datePickerButton.setIcon(dateExampleIcon); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 7, Custom Icon:"); // Create a date picker: Custom font. dateSettings = new DatePickerSettings(); dateSettings.setFontValidDate(new Font("Monospaced", Font.ITALIC | Font.BOLD, 17)); dateSettings.colorTextValidDate = new Color(0, 100, 0); dateSettings.setInitialDateToToday(); datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 8, Custom Font:"); // Create a date picker: Custom Date Format. // When creating a date pattern string for BCE dates, use "u" instead of "y" for the year. // For more details about that, see: DatePickerSettings.setFormatForDatesBeforeCommonEra(). // The various codes for the date pattern string are described at this link: dateSettings = new DatePickerSettings(); dateSettings.setFormatForDatesCommonEra("yyyy/MM/dd"); dateSettings.setFormatForDatesBeforeCommonEra("uuuu/MM/dd"); dateSettings.setInitialDateToToday(); datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 9, Custom Date Format:"); // Create a date picker: Another Custom Date Format. // When creating a date pattern string for BCE dates, use "u" instead of "y" for the year. // For more details about that, see: DatePickerSettings.setFormatForDatesBeforeCommonEra(). // The various codes for the date pattern string are described at this link: dateSettings = new DatePickerSettings(); dateSettings.setFormatForDatesCommonEra("d MMM yyyy"); dateSettings.setFormatForDatesBeforeCommonEra("d MMM uuuu"); dateSettings.setInitialDateToToday(); datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 10, Another Custom Date Format:"); // Create a date picker: Change first weekday. dateSettings = new DatePickerSettings(); dateSettings.firstDayOfWeek = DayOfWeek.MONDAY; datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 11, Set First Day Of Week (Mon):"); // Create a date picker: No empty dates. (aka null) dateSettings = new DatePickerSettings(); dateSettings.setAllowEmptyDates(false); datePicker = new DatePicker(dateSettings); datePicker.addDateChangeListener(new SampleDateChangeListener("datePicker12 (Disallow Empty Dates or Null), ")); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 12, Disallow Empty Dates:"); // Create a date picker: Disallow keyboard editing. dateSettings = new DatePickerSettings(); dateSettings.setAllowKeyboardEditing(false); dateSettings.setInitialDateToToday(); datePicker = new DatePicker(dateSettings); panel.panel1.add(datePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel1, 1, (row++ * rowMultiplier), "Date 13, Disallow Keyboard Editing:"); // This section creates TimePickers. (1 to 5) // Create some variables for repeated use. TimePickerSettings timeSettings; row = rowMultiplier; // Create a time picker: With default settings timePicker1 = new TimePicker(); panel.panel2.add(timePicker1, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 1, Default Settings:"); // Create a time picker: With No Buttons. timeSettings = new TimePickerSettings(); timeSettings.setDisplayToggleTimeMenuButton(false); timeSettings.setInitialTimeToNow(); timePicker2 = new TimePicker(timeSettings); panel.panel2.add(timePicker2, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 2, No Buttons:"); // Create a time picker: With Spinner Buttons. timeSettings = new TimePickerSettings(); timeSettings.setDisplayToggleTimeMenuButton(false); timeSettings.setDisplaySpinnerButtons(true); timeSettings.setInitialTimeToNow(); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 3, With Spinner Buttons:"); // Create a time picker: With All Buttons. timeSettings = new TimePickerSettings(); timeSettings.setDisplaySpinnerButtons(true); timeSettings.setInitialTimeToNow(); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 4, With All Buttons:"); // Create a time picker: 15 minute interval, and 24 hour clock. timeSettings = new TimePickerSettings(); timeSettings.use24HourClockFormat(); timeSettings.initialTime = LocalTime.of(15, 30); timeSettings.generatePotentialMenuTimes(TimeIncrement.FifteenMinutes, null, null); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 5, Interval 15 minutes, and 24 hour clock:"); // Create a time picker: Localized (Chinese). Locale chineseLocale = new Locale("zh"); timeSettings = new TimePickerSettings(chineseLocale); timeSettings.initialTime = LocalTime.now(); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 6, Localized (to Chinese):"); // Create a time picker: Custom button icon. // You can replace the example image with any desired image file. // See also: JButton.setPressedIcon() and JButton.setDisabledIcon(). // Get the example image icon. URL timeIconURL = FullDemo.class.getResource("/images/timepickerbutton1.png"); Image timeExampleImage = Toolkit.getDefaultToolkit().getImage(timeIconURL); ImageIcon timeExampleIcon = new ImageIcon(timeExampleImage); // Create the time picker, and apply the image icon. timeSettings = new TimePickerSettings(); timeSettings.initialTime = LocalTime.of(15, 00); timePicker = new TimePicker(timeSettings); JButton timePickerButton = timePicker.getComponentToggleTimeMenuButton(); timePickerButton.setText(""); timePickerButton.setIcon(timeExampleIcon); // Adjust the button size to fit the new icon. Dimension newTimeButtonSize = new Dimension( timeExampleIcon.getIconWidth() + 4, timeExampleIcon.getIconHeight() + 4); timePickerButton.setPreferredSize(newTimeButtonSize); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 7, Custom Icon:"); // This section creates DateTimePickers. (1 to 5) // Create a DateTimePicker: Default settings dateTimePicker1 = new DateTimePicker(); panel.panel2.add(dateTimePicker1, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "DateTimePicker 1, Default settings:"); // Create a DateTimePicker: Disallow empty dates and times. dateSettings = new DatePickerSettings(); timeSettings = new TimePickerSettings(); dateSettings.setAllowEmptyDates(false); timeSettings.setAllowEmptyTimes(false); dateTimePicker2 = new DateTimePicker(dateSettings, timeSettings); panel.panel2.add(dateTimePicker2, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "DateTimePicker 2, Disallow empty dates and times:"); // Create a DateTimePicker: With change listener. dateTimePicker3 = new DateTimePicker(); dateTimePicker3.addDateTimeChangeListener(new SampleDateTimeChangeListener("dateTimePicker3")); panel.panel2.add(dateTimePicker3, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "DateTimePicker 3, With Change Listener:"); // This section creates any remaining TimePickers. // Create a time picker: Disallow Empty Times. timeSettings = new TimePickerSettings(); timeSettings.setAllowEmptyTimes(false); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 8, Disallow Empty Times:"); // Create a time picker: With TimeChangeListener. timeSettings = new TimePickerSettings(); timePicker = new TimePicker(timeSettings); timePicker.addTimeChangeListener(new SampleTimeChangeListener("timePicker7")); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 9, With a TimeChangeListener:"); // Create a time picker: With more visible rows. timeSettings = new TimePickerSettings(); timeSettings.maximumVisibleMenuRows = 20; timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 10, With 20 visible menu rows:"); // Create a time picker: Custom Format. timeSettings = new TimePickerSettings(); timeSettings.setFormatForDisplayTime("ha"); timeSettings.setFormatForMenuTimes("ha"); timeSettings.initialTime = LocalTime.of(15, 00); timeSettings.generatePotentialMenuTimes(TimeIncrement.OneHour, null, null); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 11, Custom Format:"); // Create a time picker: With Veto Policy. timeSettings = new TimePickerSettings(); timePicker = new TimePicker(timeSettings); timeSettings.setVetoPolicy(new SampleTimeVetoPolicy()); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 12, With Veto Policy (Only 9a-5p allowed):"); // Create a time picker: Seconds precision. timeSettings = new TimePickerSettings(); timeSettings.setFormatForDisplayTime(PickerUtilities.createFormatterFromPatternString( "HH:mm:ss", timeSettings.getLocale())); timeSettings.setFormatForMenuTimes(PickerUtilities.createFormatterFromPatternString( "HH:mm", timeSettings.getLocale())); timeSettings.initialTime = LocalTime.of(15, 00, 00); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 13, Seconds precision (ISO format):"); // Create a time picker: Milliseconds precision. timeSettings = new TimePickerSettings(); timeSettings.setFormatForDisplayTime(PickerUtilities.createFormatterFromPatternString( "HH:mm:ss.SSS", timeSettings.getLocale())); timeSettings.setFormatForMenuTimes(PickerUtilities.createFormatterFromPatternString( "HH:mm", timeSettings.getLocale())); timeSettings.initialTime = LocalTime.of(15, 00, 00, 999000000); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 14, Millisecond precision (ISO format):"); // Create a time picker: Nanoseconds precision. timeSettings = new TimePickerSettings(); DateTimeFormatter displayTimeFormatter = DateTimeFormatter.ISO_LOCAL_TIME; timeSettings.setFormatForDisplayTime(displayTimeFormatter); timeSettings.setFormatForMenuTimes(PickerUtilities.createFormatterFromPatternString( "HH:mm", timeSettings.getLocale())); timeSettings.initialTime = LocalTime.of(15, 00, 00, 999999999); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "<html>Time 15, Nanosecond precision:<br/>(ISO format. Use \".\" to type nanoseconds.)</html>"); // Create a time picker: Disallow Keyboard Editing. timeSettings = new TimePickerSettings(); timeSettings.setAllowKeyboardEditing(false); timePicker = new TimePicker(timeSettings); panel.panel2.add(timePicker, getConstraints(1, (row * rowMultiplier), 1)); panel.addLabel(panel.panel2, 1, (row++ * rowMultiplier), "Time 16, Disallow Keyboard Editing:"); // This section creates any remaining DateTimePickers. // (None here at the moment.) // This section creates date pickers and labels for demonstrating the language translations. int rowMarker = 0; addLocalizedPickerAndLabel(++rowMarker, "Arabic:", "ar"); addLocalizedPickerAndLabel(++rowMarker, "Chinese:", "zh"); addLocalizedPickerAndLabel(++rowMarker, "Czech:", "cs"); addLocalizedPickerAndLabel(++rowMarker, "Danish:", "da"); addLocalizedPickerAndLabel(++rowMarker, "Dutch:", "nl"); addLocalizedPickerAndLabel(++rowMarker, "English:", "en"); addLocalizedPickerAndLabel(++rowMarker, "French:", "fr"); addLocalizedPickerAndLabel(++rowMarker, "German:", "de"); addLocalizedPickerAndLabel(++rowMarker, "Greek:", "el"); addLocalizedPickerAndLabel(++rowMarker, "Hindi:", "hi"); addLocalizedPickerAndLabel(++rowMarker, "Italian:", "it"); addLocalizedPickerAndLabel(++rowMarker, "Indonesian:", "in"); addLocalizedPickerAndLabel(++rowMarker, "Japanese:", "ja"); addLocalizedPickerAndLabel(++rowMarker, "Korean:", "ko"); addLocalizedPickerAndLabel(++rowMarker, "Polish:", "pl"); addLocalizedPickerAndLabel(++rowMarker, "Portuguese:", "pt"); addLocalizedPickerAndLabel(++rowMarker, "Romanian:", "ro"); addLocalizedPickerAndLabel(++rowMarker, "Russian:", "ru"); addLocalizedPickerAndLabel(++rowMarker, "Spanish:", "es"); addLocalizedPickerAndLabel(++rowMarker, "Swedish:", "sv"); addLocalizedPickerAndLabel(++rowMarker, "Turkish:", "tr"); addLocalizedPickerAndLabel(++rowMarker, "Vietnamese:", "vi"); // This section creates an independent CalendarPanel. // This CalendarPanel includes a calendar selection listener and a border. DatePickerSettings settings = new DatePickerSettings(); CalendarPanel calendarPanel = new CalendarPanel(settings); calendarPanel.setSelectedDate(LocalDate.now()); calendarPanel.addCalendarSelectionListener(new SampleCalendarSelectionListener()); calendarPanel.setBorder(new LineBorder(Color.lightGray)); panel.independentCalendarPanel.add(calendarPanel, CC.xy(2, 2)); // Display the frame. frame.pack(); frame.validate(); int maxWidth = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width; int maxHeight = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height; frame.setSize(maxWidth / 4 * 3, maxHeight / 8 * 7); frame.setLocation(maxWidth / 8, maxHeight / 16); frame.setVisible(true); } /** * getConstraints, This returns a grid bag constraints object that can be used for placing a * component appropriately into a grid bag layout. */ private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) { GridBagConstraints gc = new GridBagConstraints(); gc.fill = GridBagConstraints.NONE; gc.anchor = GridBagConstraints.WEST; gc.gridx = gridx; gc.gridy = gridy; gc.gridwidth = gridwidth; return gc; } /** * addLocalizedPickerAndLabel, This creates a date picker whose locale is set to the specified * language. This also sets the picker to today's date, creates a label for the date picker, and * adds the components to the language panel. */ private static void addLocalizedPickerAndLabel(int rowMarker, String labelText, String languageCode) { // Create the localized date picker and label. Locale locale = new Locale(languageCode); DatePickerSettings settings = new DatePickerSettings(locale); // Set a minimum size for the localized date pickers, to improve the look of the demo. settings.setSizeTextFieldMinimumWidth(125); settings.setSizeTextFieldMinimumWidthDefaultOverride(true); settings.setInitialDateToToday(); DatePicker localizedDatePicker = new DatePicker(settings); panel.panel4.add(localizedDatePicker, getConstraints(1, (rowMarker * rowMultiplier), 1)); panel.addLabel(panel.panel4, 1, (rowMarker * rowMultiplier), labelText); } /** * setTimeOneWithTimeTwoButtonClicked, This sets the time in time picker one, to whatever time * is currently set in time picker two. */ private static void setTimeOneWithTimeTwoButtonClicked(ActionEvent e) { LocalTime timePicker2Time = timePicker2.getTime(); timePicker1.setTime(timePicker2Time); // Display message. String message = "The timePicker1 value was set using the timePicker2 value!\n\n"; String timeString = timePicker1.getTimeStringOrSuppliedString("(null)"); String messageAddition = ("The timePicker1 value is currently set to: " + timeString + "."); panel.messageTextArea.setText(message + messageAddition); } /** * setTwoWithY2KButtonClicked, This sets the date in date picker two, to New Years Day 2000. */ private static void setTwoWithY2KButtonClicked(ActionEvent e) { // Set date picker date. LocalDate dateY2K = LocalDate.of(2000, Month.JANUARY, 1); datePicker2.setDate(dateY2K); // Display message. String dateString = datePicker2.getDateStringOrSuppliedString("(null)"); String message = "The datePicker2 date was set to New Years 2000!\n\n"; message += ("The datePicker2 date is currently set to: " + dateString + "."); panel.messageTextArea.setText(message); } /** * setOneWithTwoButtonClicked, This sets the date in date picker one, to whatever date is * currently set in date picker two. */ private static void setOneWithTwoButtonClicked(ActionEvent e) { // Set date from date picker 2. LocalDate datePicker2Date = datePicker2.getDate(); datePicker1.setDate(datePicker2Date); // Display message. String message = "The datePicker1 date was set using the datePicker2 date!\n\n"; message += getDatePickerOneDateText(); panel.messageTextArea.setText(message); } /** * setOneWithFeb31ButtonClicked, This sets the text in date picker one, to a nonexistent date * (February 31st). The last valid date in a date picker is always saved. This is a programmatic * demonstration of what happens when the user enters invalid text. */ private static void setOneWithFeb31ButtonClicked(ActionEvent e) { // Set date picker text. datePicker1.setText("February 31, 1950"); // Display message. String message = "The datePicker1 text was set to: \"" + datePicker1.getText() + "\".\n"; message += "Note: The stored date (the last valid date), did not change because" + " February never has 31 days.\n\n"; message += getDatePickerOneDateText(); panel.messageTextArea.setText(message); } /** * getOneAndShowButtonClicked, This retrieves and displays whatever date is currently set in * date picker one. */ private static void getOneAndShowButtonClicked(ActionEvent e) { // Get and display date picker text. panel.messageTextArea.setText(getDatePickerOneDateText()); } /** * clearOneAndTwoButtonClicked, This clears date picker one. */ private static void clearOneAndTwoButtonClicked(ActionEvent e) { // Clear the date pickers. datePicker1.clear(); datePicker2.clear(); // Display message. String message = "The datePicker1 and datePicker2 dates were cleared!\n\n"; message += getDatePickerOneDateText() + "\n"; String date2String = datePicker2.getDateStringOrSuppliedString("(null)"); message += ("The datePicker2 date is currently set to: " + date2String + "."); panel.messageTextArea.setText(message); } /** * getDatePickerOneDateText, This returns a string indicating the current date stored in date * picker one. */ private static String getDatePickerOneDateText() { // Create date string for date picker 1. String dateString = datePicker1.getDateStringOrSuppliedString("(null)"); return ("The datePicker1 date is currently set to: " + dateString + "."); } /** * createDemoButtons, This creates the buttons for the demo, adds an action listener to each * button, and adds each button to the display panel. */ private static void createDemoButtons() { JPanel buttonPanel = new JPanel(new WrapLayout()); panel.scrollPaneForButtons.setViewportView(buttonPanel); // Create each demo button, and add it to the panel. // Add an action listener to link it to its appropriate function. JButton showIntro = new JButton("Show Introduction Message"); showIntro.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showIntroductionClicked(e); } }); // showIntro.addActionListener(e -> showIntroductionClicked(e)); buttonPanel.add(showIntro); JButton setTwoWithY2K = new JButton("Set DatePicker Two with New Years Day 2000"); setTwoWithY2K.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setTwoWithY2KButtonClicked(e); } }); // setTwoWithY2K.addActionListener(e -> setTwoWithY2KButtonClicked(e)); buttonPanel.add(setTwoWithY2K); JButton setDateOneWithTwo = new JButton("Set DatePicker One with the date in Two"); setDateOneWithTwo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setOneWithTwoButtonClicked(e); } }); // setDateOneWithTwo.addActionListener(e -> setOneWithTwoButtonClicked(e)); buttonPanel.add(setDateOneWithTwo); JButton setOneWithFeb31 = new JButton("Set Text in DatePicker One to Feb 31, 1950"); setOneWithFeb31.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setOneWithFeb31ButtonClicked(e); } }); // setOneWithFeb31.addActionListener(e -> setOneWithFeb31ButtonClicked(e)); buttonPanel.add(setOneWithFeb31); JButton getOneAndShow = new JButton("Get and show the date in DatePicker One"); getOneAndShow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getOneAndShowButtonClicked(e); } }); // getOneAndShow.addActionListener(e -> getOneAndShowButtonClicked(e)); buttonPanel.add(getOneAndShow); JButton clearOneAndTwo = new JButton("Clear DatePickers One and Two"); clearOneAndTwo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clearOneAndTwoButtonClicked(e); } }); // clearOneAndTwo.addActionListener(e -> clearOneAndTwoButtonClicked(e)); buttonPanel.add(clearOneAndTwo); JButton toggleButton = new JButton("Toggle DatePicker One"); toggleButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { toggleDateOneButtonClicked(); } }); buttonPanel.add(toggleButton); JButton setTimeOneWithTwo = new JButton("TimePickers: Set TimePicker One with the time in Two"); setTimeOneWithTwo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setTimeOneWithTimeTwoButtonClicked(e); } }); // setTimeOneWithTwo.addActionListener(e -> setTimeOneWithTimeTwoButtonClicked(e)); buttonPanel.add(setTimeOneWithTwo); JButton timeToggleButton = new JButton("Toggle TimePicker One"); timeToggleButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { toggleTimeOneButtonClicked(); } }); buttonPanel.add(timeToggleButton); // Add a button for showing system information. JButton showSystemInformationButton = new JButton("JDK Versions"); showSystemInformationButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { showSystemInformationButtonClicked(); } }); buttonPanel.add(showSystemInformationButton); } /** * showIntroductionClicked, This displays an introduction message about the date picker. */ private static void showIntroductionClicked(ActionEvent e) { panel.messageTextArea.setText("Interface: \nMost items in a date picker are clickable. " + "These include... The buttons for previous and next month, the buttons for " + "previous and next year, the \"today\" text, the \"clear\" text, and individual " + "dates. A click on the month or year label (at the top), will open a menu for " + "changing the month or year.\n\nGeneral features: \n* Automatic " + "internationalization. \n* Relatively compact source code.\n* Creating a " + "DatePicker, TimePicker, or DateTimePicker requires only one line of code.\n" + "* Open source code base.\n\n" + "Data types: \nThe standard Java 8 time library is used to store dates, " + "and they are convertible to other data types. \n(The Java 8 time package " + "is also called \"java.time\" or \"JSR-310\", and was developed by the author " + "of Joda Time.)\n\nVeto and Highlight Policies: \nThese policies are optional. " + "A veto policy restricts the dates that can be selected. A highlight policy " + "provides a visual highlight on desired dates, with optional tooltips. If today " + "is vetoed, the \"today\" button will be grey and disabled.\n\nDate values and " + "automatic validation: \nEvery date picker stores its current text, and its last " + "valid date. The last valid date is returned when you call DatePicker.getDate(). " + "If the user types into the text field, any text that is not a valid date will " + "be displayed in red, any vetoed date will have a strikethrough, and valid " + "dates will display in black. When the focus on a date picker is lost, the text " + "is always set to match the last valid date.\n\nTimePicker basic features: \n" + "Pressing the up or down arrow keys will change the displayed time by one " + "minute. Holding down the arrow keys, or holding the (optional) timespinner " + "buttons will change the time at an accelerating rate. Clicking the time drop " + "down button (or pressing the right arrow key) will open a time selection menu. " + "The default intervals and range in the time drop down menu may optionally be " + "changed by the programmer (in the TimePickerSettings class)." + "\n\n\n"); panel.messageTextArea.setCaretPosition(0); } /** * toggleDateOneButtonClicked, This toggles (opens or closes) date picker one. */ private static void toggleDateOneButtonClicked() { datePicker1.togglePopup(); String message = "The datePicker1 calendar popup is "; message += (datePicker1.isPopupOpen()) ? "open!" : "closed!"; panel.messageTextArea.setText(message); } /** * toggleTimeOneButtonClicked, This toggles (opens or closes) time picker one. */ private static void toggleTimeOneButtonClicked() { timePicker1.togglePopup(); String message = "The timePicker1 menu popup is "; message += (timePicker1.isPopupOpen()) ? "open!" : "closed!"; panel.messageTextArea.setText(message); } /** * showSystemInformationButtonClicked, This shows the current system information. */ private static void showSystemInformationButtonClicked() { String runningJavaVersion = InternalUtilities.getJavaRunningVersionAsString(); String targetJavaVersion = InternalUtilities.getJavaTargetVersionFromPom(); String projectVersion = InternalUtilities.getProjectVersionString(); boolean isBackport = ("1.6".equals(targetJavaVersion)); String message = ""; message += "## Current configuration ##"; message += "\nLGoodDatePicker version: \"LGoodDatePicker "; message += (isBackport) ? ("Backport " + projectVersion) : (projectVersion + " (Standard)"); message += "\"."; message += "\nJava target version: Java " + targetJavaVersion; message += "\nJava running version: " + runningJavaVersion; message += "\n\nMinimum Requirements:" + "\n\"LGoodDatePicker Standard\" requires Java 1.8 (or above). " + "\n\"LGoodDatePicker Backport\" requires Java 1.6 or 1.7."; panel.messageTextArea.setText(message); } /** * SampleDateChangeListener, A date change listener provides a way for a class to receive * notifications whenever the date has changed in a DatePicker. */ private static class SampleDateChangeListener implements DateChangeListener { /** * datePickerName, This holds a chosen name for the date picker that we are listening to, * for generating date change messages in the demo. */ public String datePickerName; /** * Constructor. */ private SampleDateChangeListener(String datePickerName) { this.datePickerName = datePickerName; } /** * dateChanged, This function will be called each time that the date in the applicable date * picker has changed. Both the old date, and the new date, are supplied in the event * object. Note that either parameter may contain null, which represents a cleared or empty * date. */ @Override public void dateChanged(DateChangeEvent event) { LocalDate oldDate = event.getOldDate(); LocalDate newDate = event.getNewDate(); String oldDateString = PickerUtilities.localDateToString(oldDate, "(null)"); String newDateString = PickerUtilities.localDateToString(newDate, "(null)"); String messageStart = "\nThe date in " + datePickerName + " has changed from: "; String fullMessage = messageStart + oldDateString + " to: " + newDateString + "."; if (!panel.messageTextArea.getText().startsWith(messageStart)) { panel.messageTextArea.setText(""); } panel.messageTextArea.append(fullMessage); } } /** * SampleDateTimeChangeListener, A DateTimeChangeListener provides a way for a class to receive * notifications whenever the date or time has changed in a DateTimePicker. */ private static class SampleDateTimeChangeListener implements DateTimeChangeListener { /** * dateTimePickerName, This holds a chosen name for the component that we are listening to, * for generating time change messages in the demo. */ public String dateTimePickerName; /** * Constructor. */ private SampleDateTimeChangeListener(String dateTimePickerName) { this.dateTimePickerName = dateTimePickerName; } /** * dateOrTimeChanged, This function will be called whenever the in date or time in the * applicable DateTimePicker has changed. */ @Override public void dateOrTimeChanged(DateTimeChangeEvent event) { // Report on the overall DateTimeChangeEvent. String messageStart = "\n\nThe LocalDateTime in " + dateTimePickerName + " has changed from: ("; String fullMessage = messageStart + event.getOldDateTime() + ") to (" + event.getNewDateTime() + ")."; if (!panel.messageTextArea.getText().startsWith(messageStart)) { panel.messageTextArea.setText(""); } panel.messageTextArea.append(fullMessage); // Report on any DateChangeEvent, if one exists. DateChangeEvent dateEvent = event.getDateChangeEvent(); if (dateEvent != null) { String dateChangeMessage = "\nThe DatePicker value has changed from (" + dateEvent.getOldDate() + ") to (" + dateEvent.getNewDate() + ")."; panel.messageTextArea.append(dateChangeMessage); } // Report on any TimeChangeEvent, if one exists. TimeChangeEvent timeEvent = event.getTimeChangeEvent(); if (timeEvent != null) { String timeChangeMessage = "\nThe TimePicker value has changed from (" + timeEvent.getOldTime() + ") to (" + timeEvent.getNewTime() + ")."; panel.messageTextArea.append(timeChangeMessage); } } } /** * SampleDateVetoPolicy, A veto policy is a way to disallow certain dates from being selected in * calendar. A vetoed date cannot be selected by using the keyboard or the mouse. */ private static class SampleDateVetoPolicy implements DateVetoPolicy { /** * isDateAllowed, Return true if a date should be allowed, or false if a date should be * vetoed. */ @Override public boolean isDateAllowed(LocalDate date) { // Disallow days 7 to 11. if ((date.getDayOfMonth() >= 7) && (date.getDayOfMonth() <= 11)) { return false; } // Disallow odd numbered saturdays. if ((date.getDayOfWeek() == DayOfWeek.SATURDAY) && ((date.getDayOfMonth() % 2) == 1)) { return false; } // Allow all other days. return true; } } /** * SampleHighlightPolicy, A highlight policy is a way to visually highlight certain dates in the * calendar. These may be holidays, or weekends, or other significant dates. */ private static class SampleHighlightPolicy implements DateHighlightPolicy { /** * getHighlightInformationOrNull, Implement this function to indicate if a date should be * highlighted, and what highlighting details should be used for the highlighted date. * * If a date should be highlighted, then return an instance of HighlightInformation. If the * date should not be highlighted, then return null. * * You may (optionally) fill out the fields in the HighlightInformation class to give any * particular highlighted day a unique foreground color, background color, or tooltip text. * If the color fields are null, then the default highlighting colors will be used. If the * tooltip field is null (or empty), then no tooltip will be displayed. * * Dates that are passed to this function will never be null. */ @Override public HighlightInformation getHighlightInformationOrNull(LocalDate date) { // Highlight a chosen date, with a tooltip and a red background color. if (date.getDayOfMonth() == 25) { return new HighlightInformation(Color.red, null, "It's the 25th!"); } // Highlight all Saturdays with a unique background and foreground color. if (date.getDayOfWeek() == DayOfWeek.SATURDAY) { return new HighlightInformation(Color.orange, Color.yellow, "It's Saturday!"); } // Highlight all Sundays with default colors and a tooltip. if (date.getDayOfWeek() == DayOfWeek.SUNDAY) { return new HighlightInformation(null, null, "It's Sunday!"); } // All other days should not be highlighted. return null; } } /** * SampleTimeChangeListener, A time change listener provides a way for a class to receive * notifications whenever the time has changed in a TimePicker. */ private static class SampleTimeChangeListener implements TimeChangeListener { /** * timePickerName, This holds a chosen name for the time picker that we are listening to, * for generating time change messages in the demo. */ public String timePickerName; /** * Constructor. */ private SampleTimeChangeListener(String timePickerName) { this.timePickerName = timePickerName; } /** * timeChanged, This function will be called whenever the time in the applicable time picker * has changed. Note that the value may contain null, which represents a cleared or empty * time. */ @Override public void timeChanged(TimeChangeEvent event) { LocalTime oldTime = event.getOldTime(); LocalTime newTime = event.getNewTime(); String oldTimeString = PickerUtilities.localTimeToString(oldTime, "(null)"); String newTimeString = PickerUtilities.localTimeToString(newTime, "(null)"); String messageStart = "\nThe time in " + timePickerName + " has changed from: "; String fullMessage = messageStart + oldTimeString + " to: " + newTimeString + "."; if (!panel.messageTextArea.getText().startsWith(messageStart)) { panel.messageTextArea.setText(""); } panel.messageTextArea.append(fullMessage); } } /** * SampleTimeVetoPolicy, A veto policy is a way to disallow certain times from being selected in * the time picker. A vetoed time cannot be added to the time drop down menu. A vetoed time * cannot be selected by using the keyboard or the mouse. */ private static class SampleTimeVetoPolicy implements TimeVetoPolicy { /** * isTimeAllowed, Return true if a time should be allowed, or false if a time should be * vetoed. */ @Override public boolean isTimeAllowed(LocalTime time) { // Only allow times from 9a to 5p, inclusive. return PickerUtilities.isLocalTimeInRange( time, LocalTime.of(9, 00), LocalTime.of(17, 00), true); } } /** * SampleCalendarSelectionListener, A calendar selection listener provides a way for a class to * receive notifications whenever a date has been selected in an -independent- CalendarPanel. */ private static class SampleCalendarSelectionListener implements CalendarSelectionListener { /** * selectionChanged, This function will be called each time that a date is selected in the * independent CalendarPanel. The new and old selected dates are supplied in the event * object. These parameters may contain null, which represents a cleared or empty date. * * By intention, this function will be called even if the user selects the same value twice * in a row. This is so that the programmer can catch all events of interest. Duplicate * events can optionally be detected with the function CalendarSelectionEvent.isDuplicate(). */ @Override public void selectionChanged(CalendarSelectionEvent event) { LocalDate oldDate = event.getOldDate(); LocalDate newDate = event.getNewDate(); String oldDateString = PickerUtilities.localDateToString(oldDate, "(null)"); String newDateString = PickerUtilities.localDateToString(newDate, "(null)"); String messageStart = "\nIndependent Calendar Panel: The selected date has changed from '"; String fullMessage = messageStart + oldDateString + "' to '" + newDateString + "'. "; fullMessage += (event.isDuplicate()) ? "(Event marked as duplicate.)" : ""; if (!panel.messageTextArea.getText().startsWith(messageStart)) { panel.messageTextArea.setText(""); } panel.messageTextArea.append(fullMessage); } } }
package org.mskcc.cgds.test.web_api; import junit.framework.TestCase; import org.mskcc.cgds.dao.DaoCancerStudy; import org.mskcc.cgds.dao.DaoGeneOptimized; import org.mskcc.cgds.dao.DaoMutSig; import org.mskcc.cgds.model.CancerStudy; import org.mskcc.cgds.model.CanonicalGene; import org.mskcc.cgds.model.MutSig; import org.mskcc.cgds.scripts.ImportTypesOfCancers; import org.mskcc.cgds.scripts.ResetDatabase; import org.mskcc.cgds.util.ProgressMonitor; import org.mskcc.cgds.web_api.GetMutSig; import org.mskcc.cgds.dao.DaoException; import java.io.*; /** * @author Lennart Bastian */ public class TestGetMutSig extends TestCase { public void testGetMutSig() throws DaoException, IOException { ResetDatabase.resetDatabase(); ProgressMonitor pMonitor = new ProgressMonitor(); pMonitor.setConsoleMode(false); ImportTypesOfCancers.load(new ProgressMonitor(), new File("test_data/cancers.txt")); // changed GBM_portal to tcga_gbm CancerStudy cancerStudy = new CancerStudy("Glioblastoma TCGA", "GBM Description", "tcga_gbm", "GBM", false); DaoCancerStudy.addCancerStudy(cancerStudy); assertEquals(1, cancerStudy.getInternalId()); DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance(); CanonicalGene gene = new CanonicalGene(1956, "EGFR"); CanonicalGene gene2 = new CanonicalGene(4921, "DDR2"); daoGeneOptimized.addGene(gene); daoGeneOptimized.addGene(gene2); assertEquals("EGFR", gene.getHugoGeneSymbolAllCaps()); assertEquals(4921, gene2.getEntrezGeneId()); MutSig mutSig = new MutSig(1, gene, 1, 502500, 20, 1E-11f, 1E-8f); MutSig mutSig2 = new MutSig(1, gene2, 14, 273743, 3, 1E-11f, 1E-8f); assertTrue(1E-11f == mutSig.getpValue()); assertTrue(1E-8f == mutSig2.getqValue()); DaoMutSig.addMutSig(mutSig); DaoMutSig.addMutSig(mutSig2); StringBuffer stringBuffer = GetMutSig.getMutSig(1); } /* * this is taken directly from the WebService class, and minimally changed to function without * a writer, and HttpServletRequest, as to better suit it for a Test Class. */ private void getMutSig(String cancerStudyID, String qValueThreshold, String geneList) throws DaoException { int cancerID = Integer.parseInt(cancerStudyID); if ((qValueThreshold == null || qValueThreshold.length() == 0) && (geneList == null || geneList.length() == 0)) { StringBuffer output = GetMutSig.getMutSig(cancerID); System.err.println(output); System.err.println("exit code 0\n"); //if client enters a q_value_threshold } else if ((qValueThreshold != null || qValueThreshold.length() != 0) && (geneList == null || geneList.length() == 0)) { StringBuffer output = GetMutSig.getMutSig(cancerID, qValueThreshold, true); System.err.println(output); System.err.println("exit code 1\n"); //if client enters a gene_list } else if ((qValueThreshold == null || qValueThreshold.length() == 0) && (geneList != null || geneList.length() != 0)) { StringBuffer output = GetMutSig.getMutSig(cancerID, geneList, false); System.err.println(output); System.err.println("exit code 2\n"); } else { System.err.println("Invalid command. Please input a valid Q-Value Threshold, or Gene List. (Not Both)!"); } } }
package net.randomsync.testng.excel; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.testng.ITestNGListener; import org.testng.TestNG; import org.testng.xml.XmlSuite; public class ExcelTestNGRunner { private String source; private TestNG testng = new TestNG(); private IExcelFileParser parser; public ExcelTestNGRunner(String source) { this.source = source; } public ExcelTestNGRunner(String source, IExcelFileParser parser) { this.source = source; this.parser = parser; } public void setSource(String source) { this.source = source; } public void setTestng(TestNG testng) { this.testng = testng; } public void setParser(IExcelFileParser parser) { this.parser = parser; } public void run() { File srcFile = new File(source); File[] filesList = null; // if source is a directory, this will hold the // list of excel files // make sure the file source exists if (!srcFile.exists()) { throw new IllegalArgumentException("The source for the Excel " + "file(s) cannot be found."); } // if source is a folder, get all excel files within it if (srcFile.isDirectory()) { filesList = srcFile.listFiles(new ExcelFileNameFilter()); } else { filesList = new File[] { srcFile }; } if (this.testng == null) { this.testng = new TestNG(); } if (this.parser == null) { this.parser = new ExcelSuiteParser(); } // this will keep a list of all XmlSuites to be run List<XmlSuite> allSuites = new ArrayList<XmlSuite>(); // parse each file and each worksheet into an XmlSuite for (File file : filesList) { List<XmlSuite> suites = new ArrayList<XmlSuite>(); try { suites = parser.getXmlSuites(file, false); } catch (InvalidFormatException e) { // e.printStackTrace(); // any issues with parsing, skip this suite and continue continue; } catch (IOException e) { // e.printStackTrace(); // any issues with parsing, skip this suite and continue continue; } for (XmlSuite suite : suites) { allSuites.add(suite); } } testng.setXmlSuites(allSuites); testng.run(); } // helper methods to specify testng configuration public void setSuiteThreadPoolSize(int suiteThreadPoolSize) { if (testng != null) { testng.setSuiteThreadPoolSize(suiteThreadPoolSize); } } public void addListener(ITestNGListener listener) { if (testng != null) { testng.addListener(listener); } } public void setVerbose(int verbose) { if (testng != null) { testng.setVerbose(verbose); } } public void setPreserveOrder(boolean order) { if (testng != null) { testng.setPreserveOrder(order); } } public void setThreadCount(int threadCount) { if (testng != null) { testng.setThreadCount(threadCount); } } class ExcelFileNameFilter implements FilenameFilter { @Override public boolean accept(File file, String name) { if (name.endsWith(".xls") || name.endsWith(".xlsx")) { return true; } return false; } } }
package ca.eandb.jmist.framework.material; import ca.eandb.jmist.framework.Medium; import ca.eandb.jmist.framework.ScatteredRay; import ca.eandb.jmist.framework.SurfacePoint; import ca.eandb.jmist.framework.color.Color; import ca.eandb.jmist.framework.color.Spectrum; import ca.eandb.jmist.framework.color.WavelengthPacket; import ca.eandb.jmist.math.Point3; import ca.eandb.jmist.math.Ray3; import ca.eandb.jmist.math.Vector3; import ca.eandb.util.UnimplementedException; /** * @author Brad Kimmel */ public final class CookTorranceMaterial extends AbstractMaterial { /** Serialization version ID. */ private static final long serialVersionUID = -4693726623498649118L; private final double mSquared; private final Spectrum n; private final Spectrum k; public CookTorranceMaterial(double m, Spectrum n, Spectrum k) { this.mSquared = m * m; this.n = n; this.k = k; } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#scatter(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, boolean, ca.eandb.jmist.framework.color.WavelengthPacket, double, double, double) */ @Override public ScatteredRay scatter(SurfacePoint x, Vector3 v, boolean adjoint, WavelengthPacket lambda, double ru, double rv, double rj) { throw new UnimplementedException(); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#getScatteringPDF(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.math.Vector3, boolean, ca.eandb.jmist.framework.color.WavelengthPacket) */ @Override public double getScatteringPDF(SurfacePoint x, Vector3 in, Vector3 out, boolean adjoint, WavelengthPacket lambda) { throw new UnimplementedException(); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#bsdf(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.framework.color.WavelengthPacket) */ @Override public Color bsdf(SurfacePoint x, Vector3 in, Vector3 out, WavelengthPacket lambda) { Vector3 E = in.opposite(); Vector3 L = in; Vector3 H = E.plus(E).times(0.5).unit(); Vector3 N = x.getShadingNormal(); double HdotN = H.dot(N); double EdotH = E.dot(H); double EdotN = E.dot(N); double LdotN = L.dot(N); double tanAlpha = Math.tan(Math.acos(HdotN)); double cos4Alpha = HdotN * HdotN * HdotN * HdotN; Medium medium = x.getAmbientMedium(); Color n1 = medium.refractiveIndex(x.getPosition(), lambda); Color k1 = medium.extinctionIndex(x.getPosition(), lambda); Color n2 = n.sample(lambda); Color k2 = k.sample(lambda); Color F = MaterialUtil.reflectance(E, n1, k1, n2, k2, N); double D = Math.exp(-(tanAlpha * tanAlpha / mSquared)) / (4.0 * mSquared * cos4Alpha); double G = Math.min(1.0, Math.min(2.0 * HdotN * EdotN / EdotH, 2.0 * HdotN * LdotN / EdotH)); return F.times(D * G / EdotN); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.Medium#extinctionIndex(ca.eandb.jmist.math.Point3, ca.eandb.jmist.framework.color.WavelengthPacket) */ public Color extinctionIndex(Point3 p, WavelengthPacket lambda) { return k.sample(lambda); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.Medium#refractiveIndex(ca.eandb.jmist.math.Point3, ca.eandb.jmist.framework.color.WavelengthPacket) */ public Color refractiveIndex(Point3 p, WavelengthPacket lambda) { return n.sample(lambda); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.Medium#transmittance(ca.eandb.jmist.math.Ray3, double, ca.eandb.jmist.framework.color.WavelengthPacket) */ public Color transmittance(Ray3 ray, double distance, WavelengthPacket lambda) { return lambda.getColorModel().getBlack(lambda); } }
package org.torproject.onionoo; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ResourceServlet extends HttpServlet { public void init() { this.readSummaryFile(); } long summaryFileLastModified = 0L; boolean readSummaryFile = false; private String versionLine = null, validAfterLine = null, freshUntilLine = null; private List<String> relayLines = new ArrayList<String>(), bridgeLines = new ArrayList<String>(); private void readSummaryFile() { File summaryFile = new File("/srv/onionoo/out/summary.json"); if (!summaryFile.exists()) { readSummaryFile = false; return; } if (summaryFile.lastModified() > this.summaryFileLastModified) { this.versionLine = this.validAfterLine = this.freshUntilLine = null; this.relayLines.clear(); this.bridgeLines.clear(); try { BufferedReader br = new BufferedReader(new FileReader( summaryFile)); String line; while ((line = br.readLine()) != null) { if (line.startsWith("{\"version\":")) { this.versionLine = line; } else if (line.startsWith("\"valid_after\":")) { this.validAfterLine = line; } else if (line.startsWith("\"fresh_until\":")) { this.freshUntilLine = line; } else if (line.startsWith("\"relays\":")) { while ((line = br.readLine()) != null && !line.equals("],")) { this.relayLines.add(line); } } else if (line.startsWith("\"bridges\":")) { while ((line = br.readLine()) != null && !line.equals("]}")) { this.bridgeLines.add(line); } } } br.close(); } catch (IOException e) { return; } } this.summaryFileLastModified = summaryFile.lastModified(); this.readSummaryFile = true; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { this.readSummaryFile(); if (!this.readSummaryFile) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } String uri = request.getRequestURI(); String resourceType = null; if (uri.startsWith("/summary/")) { resourceType = "summary"; } else if (uri.startsWith("/details/")) { resourceType = "details"; } else if (uri.startsWith("/bandwidth/")) { resourceType = "bandwidth"; } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } StringBuilder sb = new StringBuilder(); if (uri.equals("/" + resourceType + "/all")) { this.writeHeader(sb); this.writeAllRelays(sb, resourceType); this.writeAllBridges(sb, resourceType); } else if (uri.equals("/" + resourceType + "/running")) { this.writeHeader(sb); this.writeRunningRelays(sb, resourceType); this.writeRunningBridges(sb, resourceType); } else if (uri.equals("/" + resourceType + "/relays")) { this.writeHeader(sb); this.writeAllRelays(sb, resourceType); this.writeNoBridges(sb); } else if (uri.equals("/" + resourceType + "/bridges")) { this.writeHeader(sb); this.writeNoRelays(sb); this.writeAllBridges(sb, resourceType); } else if (uri.startsWith("/" + resourceType + "/search/")) { String searchParameter = this.parseSearchParameter(uri.substring( ("/" + resourceType + "/search/").length())); if (searchParameter == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } this.writeHeader(sb); this.writeMatchingRelays(sb, searchParameter, resourceType); this.writeNoBridges(sb); } else if (uri.startsWith("/" + resourceType + "/lookup/")) { Set<String> fingerprintParameters = this.parseFingerprintParameters( uri.substring(("/" + resourceType + "/lookup/").length())); if (fingerprintParameters == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } this.writeHeader(sb); this.writeRelaysWithFingerprints(sb, fingerprintParameters, resourceType); this.writeBridgesWithFingerprints(sb, fingerprintParameters, resourceType); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } byte[] result = sb.toString().getBytes(); response.setHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setIntHeader("Content-Length", result.length); BufferedOutputStream output = new BufferedOutputStream( response.getOutputStream()); output.write(result); output.flush(); output.close(); } private static Pattern searchParameterPattern = Pattern.compile("^[0-9a-zA-Z\\.]{1,40}$"); private String parseSearchParameter(String parameter) { if (!searchParameterPattern.matcher(parameter).matches()) { return null; } return parameter; } private static Pattern fingerprintParameterPattern = Pattern.compile("^[a-zA-Z]+$"); private Set<String> parseFingerprintParameters(String parameter) { if (!searchParameterPattern.matcher(parameter).matches()) { return null; } Set<String> parsedFingerprints = new HashSet<String>(); if (parameter.length() != 40) { return null; } parsedFingerprints.add(parameter); return parsedFingerprints; } private void writeHeader(StringBuilder sb) { sb.append(this.versionLine + "\n"); sb.append(this.validAfterLine + "\n"); sb.append(this.freshUntilLine + "\n"); } private void writeAllRelays(StringBuilder sb, String resourceType) { sb.append("\"relays\":["); int written = 0; for (String line : this.relayLines) { String lines = this.getRelayFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } } sb.append("],\n"); } private void writeRunningRelays(StringBuilder sb, String resourceType) { sb.append("\"relays\":["); int written = 0; for (String line : this.relayLines) { if (line.contains("\"r\":true")) { String lines = this.getRelayFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } } } sb.append("\n],\n"); } private void writeNoRelays(StringBuilder sb) { sb.append("\"relays\":[\n"); sb.append("],\n"); } private void writeMatchingRelays(StringBuilder sb, String searchTerm, String resourceType) { sb.append("\"relays\":["); int written = 0; for (String line : this.relayLines) { if (line.toLowerCase().contains("\"n\":\"" + searchTerm.toLowerCase()) || ("unnamed".startsWith(searchTerm.toLowerCase()) && line.startsWith("{\"f\":")) || line.contains("\"f\":\"" + searchTerm.toUpperCase()) || line.substring(line.indexOf("\"a\":[")).contains("\"" + searchTerm)) { String lines = this.getRelayFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } } } sb.append("\n],\n"); } private void writeRelaysWithFingerprints(StringBuilder sb, Set<String> fingerprints, String resourceType) { sb.append("\"relays\":["); int written = 0; for (String line : this.relayLines) { for (String fingerprint : fingerprints) { if (line.contains("\"f\":\"" + fingerprint.toUpperCase() + "\",")) { String lines = this.getRelayFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } break; } } } sb.append("\n],\n"); } private void writeAllBridges(StringBuilder sb, String resourceType) { sb.append("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { String lines = this.getBridgeFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } } sb.append("\n]}\n"); } private void writeRunningBridges(StringBuilder sb, String resourceType) { sb.append("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { if (line.contains("\"r\":true")) { String lines = this.getBridgeFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } } } sb.append("\n]}\n"); } private void writeNoBridges(StringBuilder sb) { sb.append("\"bridges\":[\n"); sb.append("]}\n"); } private void writeBridgesWithFingerprints(StringBuilder sb, Set<String> fingerprints, String resourceType) { sb.append("\"bridges\":["); int written = 0; for (String line : this.bridgeLines) { for (String fingerprint : fingerprints) { if (line.contains("\"h\":\"" + fingerprint.toUpperCase() + "\",")) { String lines = this.getBridgeFromSummaryLine(line, resourceType); if (lines.length() > 0) { sb.append((written++ > 0 ? ",\n" : "\n") + lines); } break; } } } sb.append("\n]}\n"); } private String getRelayFromSummaryLine(String summaryLine, String resourceType) { if (resourceType.equals("summary")) { return this.writeSummaryLine(summaryLine); } else if (resourceType.equals("details")) { return this.writeRelayDetailsLines(summaryLine); } else if (resourceType.equals("bandwidth")) { return this.writeRelayBandwidthLines(summaryLine); } else { return ""; } } private String writeSummaryLine(String summaryLine) { return (summaryLine.endsWith(",") ? summaryLine.substring(0, summaryLine.length() - 1) : summaryLine); } private String writeRelayDetailsLines(String summaryLine) { String fingerprint = summaryLine.substring(summaryLine.indexOf( "\"f\":\"") + "\"f\":\"".length()); fingerprint = fingerprint.substring(0, 40); File detailsFile = new File("/srv/onionoo/out/details/" + fingerprint); StringBuilder sb = new StringBuilder(); String detailsLines = null; if (detailsFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader( detailsFile)); String line; boolean copyLines = false; while ((line = br.readLine()) != null) { if (line.startsWith("\"nickname\":")) { sb.append("{"); copyLines = true; } if (copyLines) { sb.append(line + "\n"); } } br.close(); detailsLines = sb.toString(); detailsLines = detailsLines.substring(0, detailsLines.length() - 1); } catch (IOException e) { } } if (detailsLines != null) { return detailsLines; } else { return ""; } } private String writeRelayBandwidthLines(String summaryLine) { String fingerprint = summaryLine.substring(summaryLine.indexOf( "\"f\":\"") + "\"f\":\"".length()); fingerprint = fingerprint.substring(0, 40); File detailsFile = new File("/srv/onionoo/out/bandwidth/" + fingerprint); StringBuilder sb = new StringBuilder(); String bandwidthLines = null; if (detailsFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader( detailsFile)); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); bandwidthLines = sb.toString(); } catch (IOException e) { } } if (bandwidthLines != null) { bandwidthLines = bandwidthLines.substring(0, bandwidthLines.length() - 1); return bandwidthLines; } else { return ""; } } private String getBridgeFromSummaryLine(String summaryLine, String resourceType) { if (resourceType.equals("summary")) { return this.writeSummaryLine(summaryLine); } else if (resourceType.equals("details")) { return this.writeBridgeDetailsLines(summaryLine); } else if (resourceType.equals("bandwidth")) { return this.writeBridgeBandwidthLines(summaryLine); } else { return ""; } } private String writeBridgeDetailsLines(String summaryLine) { return ""; } private String writeBridgeBandwidthLines(String summaryLine) { return ""; } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc330.Beachbot2014Java; import org.usfirst.frc330.Beachbot2014Java.commands.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.buttons.JoystickButton; /** * 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 JoystickButton shootButton; public Joystick rightJoystick; public JoystickButton manualArmButton; public JoystickButton wingsToggleButton; public JoystickButton pickupOffButton; public JoystickButton pickupForwardButton; public JoystickButton pickupReverseButton; public JoystickButton triggerCloseButton; public Joystick operatorJoystick; public KinectStick kinectJoystick; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public OI() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS kinectJoystick = new KinectStick(1); operatorJoystick = new Joystick(3); triggerCloseButton = new JoystickButton(operatorJoystick, 10); triggerCloseButton.whileHeld(new TrapShooterPistons()); pickupReverseButton = new JoystickButton(operatorJoystick, 8); pickupReverseButton.whileHeld(new PickupReverse()); pickupForwardButton = new JoystickButton(operatorJoystick, 7); pickupForwardButton.whenPressed(new PickupForwardPulse()); pickupOffButton = new JoystickButton(operatorJoystick, 5); pickupOffButton.whileHeld(new PickupOff()); wingsToggleButton = new JoystickButton(operatorJoystick, 9); wingsToggleButton.whenPressed(new WingsToggle()); manualArmButton = new JoystickButton(operatorJoystick, 2); manualArmButton.whileHeld(new ManualArm()); rightJoystick = new Joystick(2); shootButton = new JoystickButton(rightJoystick, 1); shootButton.whenPressed(new Shoot()); shiftLowButton = new JoystickButton(rightJoystick, 2); shiftLowButton.whenPressed(new ShiftLow()); leftJoystick = new Joystick(1); shiftHighButton = new JoystickButton(leftJoystick, 2); shiftHighButton.whenPressed(new ShiftHigh()); // SmartDashboard Buttons SmartDashboard.putData("ShiftHigh", new ShiftHigh()); SmartDashboard.putData("ShiftLow", new ShiftLow()); SmartDashboard.putData("Autonomous Command", new AutonomousCommand()); SmartDashboard.putData("MarsRock", new MarsRock()); SmartDashboard.putData("Shoot", new Shoot()); SmartDashboard.putData("ManualArm", new ManualArm()); SmartDashboard.putData("WingsOpen", new WingsOpen()); SmartDashboard.putData("WingsClose", new WingsClose()); SmartDashboard.putData("WingsToggle", new WingsToggle()); SmartDashboard.putData("PickupForward", new PickupForward()); SmartDashboard.putData("PickupOff", new PickupOff()); SmartDashboard.putData("PickupReverse", new PickupReverse()); SmartDashboard.putData("ReleaseShooterPistons", new ReleaseShooterPistons()); SmartDashboard.putData("TrapShooterPistons", new TrapShooterPistons()); SmartDashboard.putData("AutoPickupOn", new AutoPickupOn()); SmartDashboard.putData("PickupForwardPulse", new PickupForwardPulse()); SmartDashboard.putData("SendDefaultSmartDashboardData", new SendDefaultSmartDashboardData()); SmartDashboard.putData("ShooterOn", new ShooterOn()); SmartDashboard.putData("ShooterOff", new ShooterOff()); SmartDashboard.putData("ArmPickupPosition", new ArmPickupPosition()); SmartDashboard.putData("ArmBumperPosition", new ArmBumperPosition()); SmartDashboard.putData("ArmLoadingPosition", new ArmLoadingPosition()); SmartDashboard.putData("ArmCatchingPosition", new ArmCatchingPosition()); SmartDashboard.putData("ArmVerticalPosition", new ArmVerticalPosition()); SmartDashboard.putData("OppositeArmPickupPosition", new OppositeArmPickupPosition()); SmartDashboard.putData("OppositeArmBumperPosition", new OppositeArmBumperPosition()); SmartDashboard.putData("OppositeArmCatchingPosition", new OppositeArmCatchingPosition()); SmartDashboard.putData("OppositeArmLoadingPosition", new OppositeArmLoadingPosition()); // 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; } public KinectStick getKinectJoystick() { return kinectJoystick; } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS }
package com.axeldev; import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.IncorrectOperationException; import com.jetbrains.php.lang.lexer.PhpTokenTypes; import com.jetbrains.php.lang.psi.PhpExpressionCodeFragment; import com.jetbrains.php.lang.psi.PhpFile; import com.jetbrains.php.lang.psi.PhpPsiElementFactory; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull; public class PhpReplaceQuotesWithConcatenationIntention extends PsiElementBaseIntentionAction { public static final String FAMILY_NAME = "Replace quotes"; // TODO mention also variable concatenation, make title dynamic? public static final String INTENTION_NAME = "Replace quotes with unescaping and variable"; public static final char CHAR_VERTICAL_TAB = (char) 11; public static final char CHAR_ESC = (char) 27; private enum EscapingState { ReadingNewCharacter, ReadingPotentialEscapeSequence, ReadingDecimalCharEscape, ReadingPotentialHexCharEscape, ReadingHexCharEscape } @NotNull @Override public String getText() { return INTENTION_NAME; } @NotNull @Override public String getFamilyName() { return FAMILY_NAME; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) { PsiFile containingFile = psiElement.getContainingFile(); //noinspection SimplifiableIfStatement if (containingFile instanceof PhpExpressionCodeFragment) return false; return getPhpDoubleQuotedStringLiteralExpression(psiElement) != null; } @Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) throws IncorrectOperationException { PsiElement stringLiteralExpressionPsi = getPhpDoubleQuotedStringLiteralExpression(psiElement); String stringLiteralContent = getPhpDoubleQuotedStringRealContent(stringLiteralExpressionPsi); StringLiteralExpression phpSingleQuotedStringLiteralPsi = getPhpSingleQuotedStringLiteralPsiFromText(psiElement.getProject(), stringLiteralContent); stringLiteralExpressionPsi.replace(phpSingleQuotedStringLiteralPsi); } private PsiElement getPhpDoubleQuotedStringLiteralExpression(PsiElement psiElement) { if (psiElement instanceof PhpFile) return null; if (psiElement instanceof StringLiteralExpression) { PsiElement firstChild = psiElement.getFirstChild(); if (firstChild != null) { ASTNode astNode = firstChild.getNode(); if (astNode.getElementType() == PhpTokenTypes.STRING_LITERAL || astNode.getElementType() == PhpTokenTypes.chLDOUBLE_QUOTE) { return psiElement; } } } PsiElement parentPsi = psiElement.getParent(); return parentPsi != null ? getPhpDoubleQuotedStringLiteralExpression(parentPsi) : null; } private String getPhpDoubleQuotedStringRealContent(PsiElement psiElement) { String phpStringLiteralText = psiElement.getText(); String unescapedContent = phpStringLiteralText.substring(1, phpStringLiteralText.length() - 1); return unescapePhpDoubleQuotedNonComplexStringContent(unescapedContent); } private String unescapePhpDoubleQuotedNonComplexStringContent(String text) { StringBuilder escapedContentBuffer = new StringBuilder(); EscapingState escapingState = EscapingState.ReadingNewCharacter; StringBuilder currentEscapeBuffer = new StringBuilder(); for (char currentCharacter : text.toCharArray()) { boolean currentCharIsDigit = Character.isDigit(currentCharacter); if ((escapingState == EscapingState.ReadingPotentialEscapeSequence && currentCharIsDigit) || escapingState == EscapingState.ReadingDecimalCharEscape) { escapingState = EscapingState.ReadingDecimalCharEscape; if (currentCharIsDigit) { currentEscapeBuffer.append(currentCharacter); } if (!currentCharIsDigit || currentEscapeBuffer.length() == 3) { // sequence broken or max length reached, process current buffer and empty it escapedContentBuffer.append((char) Integer.parseInt(currentEscapeBuffer.toString())); currentEscapeBuffer.setLength(0); // stop decimal sequence reading escapingState = EscapingState.ReadingNewCharacter; if (currentCharIsDigit) { // current character has just been processed, continue with next character continue; } // else let current character be normally processed } } if (escapingState == EscapingState.ReadingPotentialEscapeSequence && currentCharacter == 'x') { // maybe hex character sequence detected, jump to next character to check escapingState = EscapingState.ReadingPotentialHexCharEscape; continue; } if (escapingState == EscapingState.ReadingPotentialHexCharEscape) { if (Character.toString(currentCharacter).matches("[0-9A-Fa-f]")) { escapingState = EscapingState.ReadingHexCharEscape; // verified it's a hex char sequence, let the character be processed as part of it } else { // output the backslash and the wrongly escaped x which finally are no part of an hex char escape escapedContentBuffer.append("\\x"); escapingState = EscapingState.ReadingNewCharacter; // let the character be normally processed as no escaping sequence in course } } if (escapingState == EscapingState.ReadingHexCharEscape) { boolean currentCharIsHex = Character.toString(currentCharacter).matches("[0-9A-Fa-f]"); if (currentCharIsHex) { currentEscapeBuffer.append(currentCharacter); } if (!currentCharIsHex || currentEscapeBuffer.length() == 2) { // sequence broken or max length reached, process current buffer escapedContentBuffer.append((char) Integer.parseInt(currentEscapeBuffer.toString(), 16)); // stop hex sequence reading escapingState = EscapingState.ReadingNewCharacter; if (currentCharIsHex) { // current character has just been processed, continue with next character continue; } // else let current character be normally processed } } if (escapingState == EscapingState.ReadingPotentialEscapeSequence) { // check if character is a valid escape sequence switch (currentCharacter) { case 'n': escapedContentBuffer.append('\n'); break; case 'r': escapedContentBuffer.append('\r'); break; case 't': escapedContentBuffer.append('\t'); break; case 'v': escapedContentBuffer.append(CHAR_VERTICAL_TAB); break; case 'e': escapedContentBuffer.append(CHAR_ESC); break; case 'f': escapedContentBuffer.append('\f'); break; case '\\': escapedContentBuffer.append('\\'); break; case '"': escapedContentBuffer.append('"'); break; default: // escape sequence was bad, so print both the backslash and the character escapedContentBuffer.append('\\'); escapedContentBuffer.append(currentCharacter); break; } // job already done, jump to next character escapingState = EscapingState.ReadingNewCharacter; continue; } if (escapingState == EscapingState.ReadingNewCharacter) { if (currentCharacter == '\\') { escapingState = EscapingState.ReadingPotentialEscapeSequence; } else { escapedContentBuffer.append(currentCharacter); } } } return escapedContentBuffer.toString(); } private StringLiteralExpression getPhpSingleQuotedStringLiteralPsiFromText(Project project, String stringContent) { String escapedPhpDoubleQuoteStringContent = EscapeForPhpSingleQuotedString(stringContent); String phpStringLiteralText = "'" + escapedPhpDoubleQuoteStringContent + "'"; return PhpPsiElementFactory.createPhpPsiFromText(project, StringLiteralExpression.class, phpStringLiteralText); } private String EscapeForPhpSingleQuotedString(String text) { @SuppressWarnings("UnnecessaryLocalVariable") String singleQuotesAndBackslashEscaped = text.replaceAll("(\\\\|')", "\\\\$1"); return singleQuotesAndBackslashEscaped; } }
package gov.nih.nci.cananolab.ui.report; /** * This class uploads a report file and assigns visibility * * @author pansu */ /* CVS $Id: SubmitReportAction.java,v 1.24 2008-08-05 22:45:01 tanq Exp $ */ import gov.nih.nci.cananolab.domain.common.LabFile; import gov.nih.nci.cananolab.domain.common.Report; import gov.nih.nci.cananolab.dto.common.LabFileBean; import gov.nih.nci.cananolab.dto.common.ReportBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException; import gov.nih.nci.cananolab.service.common.FileService; import gov.nih.nci.cananolab.service.common.impl.FileServiceLocalImpl; import gov.nih.nci.cananolab.service.particle.NanoparticleSampleService; import gov.nih.nci.cananolab.service.particle.impl.NanoparticleSampleServiceLocalImpl; import gov.nih.nci.cananolab.service.report.ReportService; import gov.nih.nci.cananolab.service.report.impl.ReportServiceLocalImpl; import gov.nih.nci.cananolab.service.report.impl.ReportServiceRemoteImpl; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.ui.document.SubmitPublicationAction; import gov.nih.nci.cananolab.ui.security.InitSecuritySetup; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.PropertyReader; import gov.nih.nci.cananolab.util.StringUtils; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Date; 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 SubmitReportAction extends BaseAnnotationAction { public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorForm theForm = (DynaValidatorForm) form; ReportBean reportBean = (ReportBean) theForm.get("file"); UserBean user = (UserBean) request.getSession().getAttribute("user"); reportBean.setupDomainFile(CaNanoLabConstants.FOLDER_REPORT, user .getLoginName()); if (!validateReportFile(request, reportBean)) { return mapping.getInputForward(); } ReportService service = new ReportServiceLocalImpl(); service.saveReport((Report) reportBean.getDomainFile(), reportBean .getParticleNames(), reportBean.getNewFileData()); // set visibility AuthorizationService authService = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); authService.assignVisibility(reportBean.getDomainFile().getId() .toString(), reportBean.getVisibilityGroups()); InitReportSetup.getInstance().persistReportDropdowns(request, reportBean); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.submitReport.file", reportBean.getDomainFile().getTitle()); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); saveMessages(request, msgs); forward = mapping.findForward("success"); HttpSession session = request.getSession(); String particleId = request.getParameter("particleId"); if (particleId==null ||particleId.length()==0) { Object particleIdObj = session.getAttribute("particleId"); if (particleIdObj!=null) { particleId = particleIdObj.toString(); request.setAttribute("particleId", particleId); }else { request.removeAttribute("particleId"); } } if (particleId != null && particleId.length() > 0) { NanoparticleSampleService sampleService = new NanoparticleSampleServiceLocalImpl(); ParticleBean particleBean = sampleService .findNanoparticleSampleById(particleId); setupDataTree(particleBean, request); forward = mapping.findForward("particleSuccess"); } session.removeAttribute("particleId"); return forward; } public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String particleId = request.getParameter("particleId"); if (particleId != null) { session.setAttribute("particleId", particleId); }else { //if it is not calling from particle, remove previous set attribute if applicable session.removeAttribute("particleId"); } InitReportSetup.getInstance().setReportDropdowns(request); // if particleId is available direct to particle specific page ActionForward forward = mapping.getInputForward(); if (particleId != null) { forward = mapping.findForward("particleSubmitReport"); request.setAttribute("particleId", particleId); }else { request.removeAttribute("particleId"); } return forward; } public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String particleId = request.getParameter("particleId"); if (particleId != null) { session.setAttribute("particleId", particleId); }else { session.removeAttribute("particleId"); } DynaValidatorForm theForm = (DynaValidatorForm) form; String reportId = request.getParameter("reportId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); ReportService reportService = new ReportServiceLocalImpl(); ReportBean reportBean = reportService.findReportById(reportId); FileService fileService = new FileServiceLocalImpl(); fileService.retrieveVisibility(reportBean, user); theForm.set("file", reportBean); InitReportSetup.getInstance().setReportDropdowns(request); // if particleId is available direct to particle specific page ActionForward forward = mapping.getInputForward(); if (particleId != null) { forward = mapping.findForward("particleSubmitReport"); request.setAttribute("particleId", particleId); }else { request.removeAttribute("particleId"); } return forward; } public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; HttpSession session = request.getSession(); UserBean user = (UserBean) session.getAttribute("user"); String reportId = request.getParameter("reportId"); String location = request.getParameter("location"); ReportService reportService = null; if (location.equals("local")) { reportService = new ReportServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); reportService = new ReportServiceRemoteImpl(serviceUrl); } ReportBean reportBean = reportService.findReportById(reportId); if (location.equals("local")) { // retrieve visibility FileService fileService = new FileServiceLocalImpl(); LabFileBean labFileBean = new LabFileBean(reportBean.getDomainFile()); fileService.retrieveVisibility(labFileBean, user); if (labFileBean.isHidden()){ reportBean.setHidden(true); }else{ reportBean.setHidden(false); } } theForm.set("file", reportBean); InitReportSetup.getInstance().setReportDropdowns(request); // if particleId is available direct to particle specific page String particleId = request.getParameter("particleId"); ActionForward forward = mapping.findForward("view"); if (particleId != null) { forward = mapping.findForward("particleViewReport"); } return forward; } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String location = request.getParameter("location"); ReportService reportService = null; if (location.equals("local")) { reportService = new ReportServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); reportService = new ReportServiceRemoteImpl(serviceUrl); } String reportId = request.getParameter("reportId"); ReportBean reportBean = reportService.findReportById(reportId); DynaValidatorForm theForm = (DynaValidatorForm) form; theForm.set("file", reportBean); String particleId = request.getParameter("particleId"); String submitType = request.getParameter("submitType"); String requestUrl = request.getRequestURL().toString(); String printLinkURL = requestUrl + "?page=0&dispatch=printDetailView&particleId=" + particleId + "&reportId=" + reportId + "&submitType=" + submitType + "&location=" + location; request.getSession().setAttribute("printDetailViewLinkURL", printLinkURL); return mapping.findForward("particleDetailView"); } public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_DOCUMENT); } private boolean validateReportFile(HttpServletRequest request, ReportBean reportBean) throws Exception { ActionMessages msgs = new ActionMessages(); if (!validateFileBean(request, msgs, reportBean)) { return false; } return true; } protected boolean validateFileBean(HttpServletRequest request, ActionMessages msgs, LabFileBean fileBean) { boolean noErrors = true; LabFile labfile = fileBean.getDomainFile(); if (labfile.getUriExternal()) { if (fileBean.getExternalUrl() == null || fileBean.getExternalUrl().trim().length() == 0) { ActionMessage msg = new ActionMessage("errors.required", "external url"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); noErrors = false; } } else{ //all empty if ((fileBean.getUploadedFile()==null || fileBean.getUploadedFile().toString().trim().length()==0) && (fileBean.getExternalUrl()==null || fileBean.getExternalUrl().trim().length()==0) && (fileBean.getDomainFile()==null || fileBean.getDomainFile().getName()==null)){ ActionMessage msg = new ActionMessage("errors.required", "uploaded file"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); noErrors = false; //the case that user switch from url to upload file, but no file is selected }else if ((fileBean.getUploadedFile() == null || fileBean.getUploadedFile().getFileName().length() == 0) && fileBean.getExternalUrl()!=null && fileBean.getExternalUrl().trim().length()>0) { ActionMessage msg = new ActionMessage("errors.required", "uploaded file"); msgs.add(ActionMessages.GLOBAL_MESSAGE, msg); this.saveErrors(request, msgs); noErrors = false; } } return noErrors; } //if report is the first record of the delete list, SubmitReportAction is called public ActionForward deleteAll(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SubmitPublicationAction pubAction = new SubmitPublicationAction(); return pubAction.deleteAll(mapping, form, request, response); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Object particleIdObj = session.getAttribute("particleId"); String particleId = null; if (particleIdObj!=null) { particleId = particleIdObj.toString(); request.setAttribute("particleId", particleId); }else { request.removeAttribute("particleId"); } ActionForward forward = null; if (particleId != null) { forward = mapping.findForward("particleSubmitReport"); }else { forward = mapping.findForward("documentSubmitReport"); } return forward; } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String location = request.getParameter("location"); ReportService reportService = null; if (location.equals("local")) { reportService = new ReportServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); reportService = new ReportServiceRemoteImpl(serviceUrl); } String reportId = request.getParameter("reportId"); ReportBean reportBean = reportService.findReportById(reportId); DynaValidatorForm theForm = (DynaValidatorForm) form; theForm.set("file", reportBean); String title = reportBean.getDomainFile().getTitle(); if (title!=null && title.length()>10) { title = title.substring(0,10); } String fileName = this.getExportFileName(title, "detailView"); response.setContentType("application/vnd.ms-execel"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + ".xls\""); setReportFileFullPath(request, reportBean, location); ReportService service = null; if (location.equals("local")) { service = new ReportServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); service = new ReportServiceRemoteImpl( serviceUrl); } service.exportDetail(reportBean, response.getOutputStream()); return null; } private String getExportFileName(String titleName, String viewType) { List<String> nameParts = new ArrayList<String>(); nameParts.add(titleName); nameParts.add("Report"); nameParts.add(viewType); nameParts.add(StringUtils.convertDateToString(new Date(), "yyyyMMdd_HH-mm-ss-SSS")); String exportFileName = StringUtils.join(nameParts, "_"); return exportFileName; } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String location = request.getParameter("location"); ReportService reportService = null; if (location.equals("local")) { reportService = new ReportServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); reportService = new ReportServiceRemoteImpl(serviceUrl); } String reportId = request.getParameter("reportId"); ReportBean reportBean = reportService.findReportById(reportId); DynaValidatorForm theForm = (DynaValidatorForm) form; theForm.set("file", reportBean); return mapping.findForward("reportDetailPrintView"); } private void setReportFileFullPath(HttpServletRequest request, ReportBean reportBean, String location) throws Exception { if (location.equals("local")) { // set file full path if (!reportBean.getDomainFile().getUriExternal()) { String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); reportBean.setFullPath(fileRoot + File.separator + reportBean.getDomainFile().getUri()); } else { reportBean.setFullPath(reportBean.getDomainFile().getUri()); } } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); URL localURL = new URL(request.getRequestURL().toString()); String actionPath = localURL.getPath(); URL remoteUrl = new URL(serviceUrl); String remoteServerHostUrl = remoteUrl.getProtocol() + ": + remoteUrl.getHost() + ":" + remoteUrl.getPort(); String remoteDownloadUrlBase = remoteServerHostUrl + actionPath + "?dispatch=download&location=local&fileId="; String remoteDownloadUrl = remoteDownloadUrlBase + reportBean.getDomainFile().getId().toString(); reportBean.setFullPath(remoteDownloadUrl); } } }
package org.apache.commons.graph.algorithm.search; /** * This class does a Depth First Search. It visits all of the children nodes * before moving to the siblling nodes. */ import java.util.Map; import java.util.HashMap; import java.util.Iterator; import org.apache.commons.graph.*; /** * Description of the Class */ public class DFS { private Map colors = new HashMap();// VERTEX X COLOR /** * Description of the Field */ public final static String WHITE = "white"; /** * Description of the Field */ public final static String BLACK = "black"; /** * Description of the Field */ public final static String GRAY = "gray"; /** * Constructor for the DFS object */ public DFS() { } /** * Gets the color attribute of the DFS object */ public String getColor(Vertex v) { String color = (String)colors.get(v); return color != null ? color : WHITE; } /** * Description of the Method */ private void visitEdge(DirectedGraph graph, Edge e, Visitor visitor) { visitor.discoverEdge(e); Vertex v = graph.getTarget(e); if (getColor(v) == WHITE) { visitVertex(graph, v, visitor); } visitor.finishEdge(e); } /** * Description of the Method */ private void visitVertex(DirectedGraph graph, Vertex v, Visitor visitor) { colors.put(v, GRAY); visitor.discoverVertex(v); Iterator edges = graph.getOutbound(v).iterator(); while (edges.hasNext()) { Edge e = (Edge) edges.next(); visitEdge(graph, e, visitor); } visitor.finishVertex(v); colors.put(v, BLACK); } /** * visit - Visits the graph */ public void visit(DirectedGraph graph, Vertex root, Visitor visitor) { colors.clear(); visitor.discoverGraph(graph); visitVertex(graph, root, visitor); visitor.finishGraph(graph); } /** * visit - Visits all nodes in the graph. */ public void visit( DirectedGraph graph, Visitor visitor ) { colors.clear(); visitor.discoverGraph( graph ); Iterator vertices = graph.getVertices().iterator(); while (vertices.hasNext()) { Vertex v = (Vertex) vertices.next(); if (colors.get( v ) == WHITE) { visitVertex( graph, v, visitor ); } } visitor.finishGraph( graph ); } }
package imagej.process.operation; import imagej.process.Span; import imagej.process.TypeManager; import mpicbg.imglib.image.Image; import mpicbg.imglib.type.numeric.RealType; public class SetPlaneOperation<T extends RealType<T>> extends PositionalSingleCursorRoiOperation<T> { public static enum PixelType {BYTE,SHORT,INT,FLOAT,DOUBLE,LONG}; // set in constructor private PixelType pixType; private PixelReader reader; // set before iteration private int pixNum; private boolean isIntegral; public SetPlaneOperation(Image<T> theImage, int[] origin, Object pixels, PixelType inputType, boolean isUnsigned) { super(theImage, origin, Span.singlePlane(theImage.getDimension(0), theImage.getDimension(1), theImage.getNumDimensions())); this.pixType = inputType; switch (pixType) { case BYTE: if (isUnsigned) this.reader = new UnsignedByteReader(pixels); else this.reader = new ByteReader(pixels); break; case SHORT: if (isUnsigned) this.reader = new UnsignedShortReader(pixels); else this.reader = new ShortReader(pixels); break; case INT: if (isUnsigned) this.reader = new UnsignedIntReader(pixels); else this.reader = new IntReader(pixels); break; case LONG: this.reader = new LongReader(pixels); break; case FLOAT: this.reader = new FloatReader(pixels); break; case DOUBLE: this.reader = new DoubleReader(pixels); break; default: throw new IllegalArgumentException("unknown pixel type"); } } @Override public void beforeIteration(RealType<T> type) { this.pixNum = 0; this.isIntegral = TypeManager.isIntegralType(type); } @Override public void insideIteration(int[] position, RealType<T> sample) { double pixelValue = reader.getValue(this.pixNum++); if (this.isIntegral) pixelValue = TypeManager.boundValueToType(sample, pixelValue); sample.setReal(pixelValue); } @Override public void afterIteration() { } private interface PixelReader { double getValue(int i); } private class ByteReader implements PixelReader { byte[] pixels; ByteReader(Object pixels) { this.pixels = (byte[]) pixels; } public double getValue(int i) { return pixels[i]; } } private class UnsignedByteReader implements PixelReader { byte[] pixels; UnsignedByteReader(Object pixels) { this.pixels = (byte[]) pixels; } public double getValue(int i) { double pixel = pixels[i]; if (pixel < 0) pixel = 256.0 + pixel; return pixel; } } private class ShortReader implements PixelReader { short[] pixels; ShortReader(Object pixels) { this.pixels = (short[]) pixels; } public double getValue(int i) { return pixels[i]; } } private class UnsignedShortReader implements PixelReader { short[] pixels; UnsignedShortReader(Object pixels) { this.pixels = (short[]) pixels; } public double getValue(int i) { double pixel = pixels[i]; if (pixel < 0) pixel = 65536.0 + pixel; return pixel; } } private class IntReader implements PixelReader { int[] pixels; IntReader(Object pixels) { this.pixels = (int[]) pixels; } public double getValue(int i) { return pixels[i]; } } private class UnsignedIntReader implements PixelReader { int[] pixels; UnsignedIntReader(Object pixels) { this.pixels = (int[]) pixels; } public double getValue(int i) { double pixel = pixels[i]; if (pixel < 0) pixel = 4294967296.0 + pixel; return pixel; } } private class LongReader implements PixelReader { long[] pixels; LongReader(Object pixels) { this.pixels = (long[]) pixels; } public double getValue(int i) { return pixels[i]; } } private class FloatReader implements PixelReader { float[] pixels; FloatReader(Object pixels) { this.pixels = (float[]) pixels; } public double getValue(int i) { return pixels[i]; } } private class DoubleReader implements PixelReader { double[] pixels; DoubleReader(Object pixels) { this.pixels = (double[]) pixels; } public double getValue(int i) { return pixels[i]; } } }
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Mustafa_Input * User makes query and saving in this servlet. */ @WebServlet("/Mustafa_Input") public class Mustafa_Input extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Mustafa_Input() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String select = request.getParameter("menu"); if(select == null){ out.println("<p><a href=Mustafa>Go back!<a></p>"); out.println("<form action='Mustafa_Input' method='get'><p>Enter a population</p>"+ "<input type='hidden' name='menu' value='query'/>"+ "<input type='text' name='input'><br><input type='submit' value='Submit'></form>"); } else if (select.equals("query")){ Integer myQuery = Integer.parseInt(request.getParameter("input")); ArrayList<Mustafa_Data> queryData = Mustafa_DatabaseConnection.makeQuery(myQuery); if (queryData.size()>0){ out.println("<p>There exists countries whose population is exactly your query.</p> "); }else{ out.println("<p>There is no country whose population is exactly your query.</p>"); } Integer minIdx = 0; Integer minVal = Integer.MAX_VALUE; ArrayList<Mustafa_Data> myData = Mustafa_DatabaseConnection.getData(); for(int i = 0; i<myData.size(); i++){ Integer absDiff = Math.abs(myQuery - myData.get(i).population); if (absDiff<minVal) { minIdx = i; minVal = absDiff; } } ArrayList<Mustafa_Data> results = new ArrayList<Mustafa_Data>(); results.add(myData.get(minIdx)); for(int i = 0; i< 20; i++){ if(minIdx == (myData.size()-1)){ results.add(myData.get(minIdx-1)); myData.remove(minIdx-1); minIdx }else if(minIdx == 0){ results.add(myData.get(minIdx+1)); myData.remove(minIdx+1); } else if(Math.abs(myQuery - myData.get(minIdx-1).population)<Math.abs(myQuery - myData.get(minIdx+1).population)){ results.add(myData.get(minIdx-1)); myData.remove(minIdx-1); minIdx } else { results.add(myData.get(minIdx+1)); myData.remove(minIdx+1); } } out.println("<form action='Mustafa_Input' method='get'>"); out.println("<table>"); out.println("<tr>"); out.println("<th><strong>Check</strong></th>"); out.println("<th><strong>Population</strong></th>"); out.println("<th align='left'><strong>Country</strong></th>"); out.println("</tr>"); for(int i = 0; i < results.size();i++){ out.println("<tr>"); out.println("<td><input type='checkbox' name='checkbox_" + i + "' value='checked' /></td>"); out.println("<td align='right'>"+ results.get(i).population +"</td>"); out.println("<td align='left'>"+ results.get(i).country +"</td>"); out.println("</tr>"); } out.println("</table>"); out.println("<input type='hidden' name='input' value='"+myQuery+"'/>"); out.println("<input type='hidden' name='menu' value='save'/><input type='submit' value='Save'></form>"); out.println("<br>Check the checkboxes and click Save button to save some of these countries."); out.println("<p><a href=Mustafa>Go back!<a></p>"); } else if(select.equals("save")){ Integer myQuery = Integer.parseInt(request.getParameter("input")); ArrayList<Mustafa_Data> myData = Mustafa_DatabaseConnection.getData(); Integer minIdx = 0; Integer minVal = Integer.MAX_VALUE; for(int i = 0; i<myData.size(); i++){ Integer absDiff = Math.abs(myQuery - myData.get(i).population); if (absDiff<minVal) { minIdx = i; minVal = absDiff; } } ArrayList<Mustafa_Data> results = new ArrayList<Mustafa_Data>(); results.add(myData.get(minIdx)); for(int i = 0; i< 20; i++){ if(Math.abs(myQuery - myData.get(minIdx-1).population)<Math.abs(myQuery - myData.get(minIdx+1).population)){ results.add(myData.get(minIdx-1)); myData.remove(minIdx-1); minIdx } else { results.add(myData.get(minIdx+1)); myData.remove(minIdx+1); } } for (int i = 0; i<results.size();i++){ if(request.getParameter("checkbox_"+i)!=null){ String isChecked = request.getParameter("checkbox_"+i); if (isChecked.equals("checked")) Mustafa_DatabaseConnection.saveData(results.get(i)); } } out.println("<p>Saved</p>"); out.println("<p><a href=Mustafa>Go back!<a></p>"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package net.hawkengine.model; import net.hawkengine.model.enums.RunIf; import net.hawkengine.model.enums.Status; import net.hawkengine.model.enums.TaskType; import java.time.Duration; import java.time.LocalDateTime; public class Task extends DbEntry{ private TaskDefinition taskDefinition; private String jobId; private String stageId; private String pipelineId; private RunIf runIfCondition; private TaskType type; private Status status; private String output; private LocalDateTime startTime; private LocalDateTime endTime; private Duration duration; public Task() { this.startTime = LocalDateTime.now(); } public TaskDefinition getTaskDefinition() { return this.taskDefinition; } public void setTaskDefinition(TaskDefinition taskDefinition) { this.taskDefinition = taskDefinition; } public String getJobId() { return this.jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getStageId() { return this.stageId; } public void setStageId(String stageId) { this.stageId = stageId; } public String getPipelineId() { return this.pipelineId; } public void setPipelineId(String pipelineId) { this.pipelineId = pipelineId; } public RunIf getRunIfCondition() { return this.runIfCondition; } public void setRunIfCondition(RunIf runIfCondition) { this.runIfCondition = runIfCondition; } public TaskType getType() { return this.type; } public void setType(TaskType type) { this.type = type; } public Status getStatus() { return this.status; } public void setStatus(Status status) { this.status = status; } public String getOutput() { return this.output; } public void setOutput(String output) { this.output = output; } public LocalDateTime getStartTime() { return this.startTime; } public void setStartTime(LocalDateTime startTime) { this.startTime = startTime; } public LocalDateTime getEndTime() { return this.endTime; } public void setEndTime(LocalDateTime endTime) { this.endTime = endTime; } public Duration getDuration() { return this.duration; } public void setDuration(Duration duration) { this.duration = duration; } }
package com.jwetherell.algorithms.data_structures; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; public class IntervalTree<O extends Object> { private Interval<O> root = null; private static final Comparator<IntervalData<?>> startComparator = new Comparator<IntervalData<?>>() { /** * {@inheritDoc} */ @Override public int compare(IntervalData<?> arg0, IntervalData<?> arg1) { // Compare start first if (arg0.start < arg1.start) return -1; if (arg1.start < arg0.start) return 1; // Then end if (arg0.end < arg1.end) return -1; if (arg1.end < arg0.end) return 1; // if they have the same start and end they must be equal return 0; } }; private static final Comparator<IntervalData<?>> endComparator = new Comparator<IntervalData<?>>() { /** * {@inheritDoc} */ @Override public int compare(IntervalData<?> arg0, IntervalData<?> arg1) { // Compare end first if (arg0.end < arg1.end) return -1; if (arg1.end < arg0.end) return 1; // Then start if (arg0.start < arg1.start) return -1; if (arg1.start < arg0.start) return 1; // if they have the same start and end they must be equal return 0; } }; /** * Create interval tree from list of IntervalData objects; * * @param intervals * is a list of IntervalData objects */ public IntervalTree(List<IntervalData<O>> intervals) { if (intervals.size() <= 0) return; root = createFromList(intervals); } protected static final <O extends Object> Interval<O> createFromList(List<IntervalData<O>> intervals) { Interval<O> newInterval = new Interval<O>(); if (intervals.size()==1) { IntervalData<O> middle = intervals.get(0); newInterval.center = ((middle.start + middle.end) / 2); newInterval.overlap.add(middle); } else { int half = intervals.size() / 2; IntervalData<O> middle = intervals.get(half); newInterval.center = ((middle.start + middle.end) / 2); List<IntervalData<O>> leftIntervals = new ArrayList<IntervalData<O>>(); List<IntervalData<O>> rightIntervals = new ArrayList<IntervalData<O>>(); for (IntervalData<O> interval : intervals) { if (interval.end < newInterval.center) { leftIntervals.add(interval); } else if (interval.start > newInterval.center) { rightIntervals.add(interval); } else { newInterval.overlap.add(interval); } } if (leftIntervals.size() > 0) newInterval.left = createFromList(leftIntervals); if (rightIntervals.size() > 0) newInterval.right = createFromList(rightIntervals); } return newInterval; } /** * Stabbing query * * @param index * to query for. * @return data at index. */ public IntervalData<O> query(long index) { return root.query(index); } /** * Range query * * @param start * of range to query for. * @param end * of range to query for. * @return data for range. */ public IntervalData<O> query(long start, long end) { return root.query(start, end); } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(IntervalTreePrinter.getString(this)); return builder.toString(); } protected static class IntervalTreePrinter { public static <O extends Object> String getString(IntervalTree<O> tree) { if (tree.root == null) return "Tree has no nodes."; return getString(tree.root, "", true); } private static <O extends Object> String getString(Interval<O> interval, String prefix, boolean isTail) { StringBuilder builder = new StringBuilder(); builder.append(prefix + (isTail ? " " : " ") + interval.toString() + "\n"); List<Interval<O>> children = new ArrayList<Interval<O>>(); if (interval.left != null) children.add(interval.left); if (interval.right != null) children.add(interval.right); if (children.size() > 0) { for (int i = 0; i < children.size() - 1; i++) { builder.append(getString(children.get(i), prefix + (isTail ? " " : " "), false)); } if (children.size() > 0) { builder.append(getString(children.get(children.size() - 1), prefix + (isTail ? " " : " "), true)); } } return builder.toString(); } } public static final class Interval<O> { private long center = Long.MIN_VALUE; private Interval<O> left = null; private Interval<O> right = null; private Set<IntervalData<O>> overlap = new TreeSet<IntervalData<O>>(startComparator); /** * Stabbing query * * @param index * to query for. * @return data at index. */ public IntervalData<O> query(long index) { IntervalData<O> results = null; if (index < center) { // overlap is sorted by start point for (IntervalData<O> data : overlap) { if (data.start > index) break; IntervalData<O> temp = data.query(index); if (results == null && temp != null) results = temp; else if (temp != null) results.combined(temp); } } else if (index >= center) { // overlapEnd is sorted by end point Set<IntervalData<O>> overlapEnd = new TreeSet<IntervalData<O>>(endComparator); overlapEnd.addAll(overlap); for (IntervalData<O> data : overlapEnd) { if (data.end < index) break; IntervalData<O> temp = data.query(index); if (results == null && temp != null) results = temp; else if (temp != null) results.combined(temp); } } if (index < center) { if (left != null) { IntervalData<O> temp = left.query(index); if (results == null && temp != null) results = temp; else if (temp != null) results.combined(temp); } } else if (index >= center) { if (right != null) { IntervalData<O> temp = right.query(index); if (results == null && temp != null) results = temp; else if (temp != null) results.combined(temp); } } return results; } /** * Range query * * @param start * of range to query for. * @param end * of range to query for. * @return data for range. */ public IntervalData<O> query(long start, long end) { IntervalData<O> results = null; for (IntervalData<O> data : overlap) { if (data.start > end) break; IntervalData<O> temp = data.query(start, end); if (results == null && temp != null) results = temp; else if (temp != null) results.combined(temp); } if (left != null && start < center) { IntervalData<O> temp = left.query(start, end); if (temp != null && results == null) results = temp; else if (temp != null) results.combined(temp); } if (right != null && end >= center) { IntervalData<O> temp = right.query(start, end); if (temp != null && results == null) results = temp; else if (temp != null) results.combined(temp); } return results; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Center=").append(center); builder.append(" Set=").append(overlap); return builder.toString(); } } /** * Data structure representing an interval. */ public static final class IntervalData<O> implements Comparable<IntervalData<O>> { private long start = Long.MIN_VALUE; private long end = Long.MAX_VALUE; private Set<O> set = new TreeSet<O>(); // Sorted /** * Interval data using O as it's unique identifier * * @param object * Object which defines the interval data */ public IntervalData(long index, O object) { this.start = index; this.end = index; this.set.add(object); } /** * Interval data using O as it's unique identifier * * @param object * Object which defines the interval data */ public IntervalData(long start, long end, O object) { this.start = start; this.end = end; this.set.add(object); } /** * Interval data list which should all be unique * * @param list * of interval data objects */ public IntervalData(long start, long end, Set<O> set) { this.start = start; this.end = end; this.set = set; // Make sure they are unique Iterator<O> iter = set.iterator(); while (iter.hasNext()) { O obj1 = iter.next(); O obj2 = null; if (iter.hasNext()) obj2 = iter.next(); if (obj1.equals(obj2)) throw new InvalidParameterException("Each interval data in the list must be unique."); } } /** * Clear the indices. */ public void clear() { this.start = Long.MIN_VALUE; this.end = Long.MAX_VALUE; this.set.clear(); } /** * Combined this IntervalData with data. * * @param data * to combined with. * @return Data which represents the combination. */ public IntervalData<O> combined(IntervalData<O> data) { if (data.start < this.start) this.start = data.start; if (data.end > this.end) this.end = data.end; this.set.addAll(data.set); return this; } /** * Deep copy of data. * * @return deep copy. */ public IntervalData<O> copy() { Set<O> listCopy = new TreeSet<O>(); listCopy.addAll(set); return new IntervalData<O>(start, end, listCopy); } /** * Query inside this data object. * * @param start * of range to query for. * @param end * of range to query for. * @return Data queried for or NULL if it doesn't match the query. */ public IntervalData<O> query(long index) { if (index < this.start || index > this.end) { // Ignore } else { return copy(); } return null; } /** * Query inside this data object. * * @param start * of range to query for. * @param end * of range to query for. * @return Data queried for or NULL if it doesn't match the query. */ public IntervalData<O> query(long start, long end) { if (end < this.start || start > this.end) { // Ignore } else { return copy(); } return null; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (!(obj instanceof IntervalData)) return false; @SuppressWarnings("unchecked") IntervalData<O> data = (IntervalData<O>) obj; if (this.start == data.start && this.end == data.end) { if (this.set.size() != data.set.size()) return false; for (O o : set) { if (!data.set.contains(o)) return false; } return true; } return false; } /** * {@inheritDoc} */ @Override public int compareTo(IntervalData<O> d) { if (this.end < d.end) return -1; if (d.end < this.end) return 1; return 0; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(start).append("->").append(end); builder.append(" set=").append(set); return builder.toString(); } } }
package com.redhat.ceylon.common.tools; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import com.redhat.ceylon.common.FileUtil; import com.redhat.ceylon.common.ModuleUtil; import com.redhat.ceylon.common.tool.ToolUsageError; public class SourceArgumentsResolver { private final Iterable<File> sourceDirs; private final Iterable<File> resourceDirs; private final String[] sourceSuffixes; private File cwd; private boolean expandSingleSources; private List<String> srcModules; private List<String> resModules; private List<File> srcFiles; private List<File> resFiles; public SourceArgumentsResolver(Iterable<File> sourceDirs, Iterable<File> resourceDirs, String... sourceSuffixes) { this.sourceDirs = sourceDirs; this.resourceDirs = resourceDirs; this.sourceSuffixes = sourceSuffixes; this.srcModules = new LinkedList<String>(); this.resModules = new LinkedList<String>(); this.srcFiles = new LinkedList<File>(); this.resFiles = new LinkedList<File>(); } public SourceArgumentsResolver cwd(File cwd) { this.cwd = cwd; return this; } /** * Setting this to true will cause single source files to be expanded to include * all other files belonging to their module. This is specifically done for * compiler backends that are unable to perform single-file compilations. * @param expandSingleSources * @return This object for chaining */ public SourceArgumentsResolver expandSingleSources(boolean expandSingleSources) { this.expandSingleSources = expandSingleSources; return this; } public List<String> getSourceModules() { return srcModules; } public List<String> getResourceModules() { return resModules; } public List<File> getSourceFiles() { return srcFiles; } public List<File> getResourceFiles() { return resFiles; } public void expandAndParse(List<String> modulesOrFiles) throws IOException { List<String> expandedModulesOrFiles = ModuleWildcardsHelper.expandWildcards(sourceDirs , modulesOrFiles); parse(expandedModulesOrFiles); } public void parse(List<String> modulesOrFiles) throws IOException { HashSet<String> srcMods = new HashSet<String>(); HashSet<String> resMods = new HashSet<String>(); HashSet<String> singleFileMods = new HashSet<String>(); srcFiles = new LinkedList<File>(); resFiles = new LinkedList<File>(); Iterable<File> srcs = FileUtil.applyCwd(cwd, sourceDirs); Iterable<File> resrcs = FileUtil.applyCwd(cwd, resourceDirs); for (String moduleOrFile : modulesOrFiles) { File file = new File(moduleOrFile); if (file.isFile()) { // It's a single (re)source file instead of a module name, so let's check // if it's really located in one of the defined (re)source folders File path; if (hasAcceptedSuffix(file, sourceSuffixes)) { path = FileUtil.selectPath(srcs, moduleOrFile); if (path == null) { String srcPath = sourceDirs.toString(); throw new ToolUsageError(CeylonToolMessages.msg("error.not.in.source.path", moduleOrFile, srcPath)); } if (!expandSingleSources) { srcFiles.add(file); } else { // Instead of adding the source file itself we remember // its module name and at the end we expand that and // add all its files singleFileMods.add(moduleName(srcs, path, file)); } // Determine the module path from the file path srcMods.add(moduleName(srcs, path, file)); } else { if (resrcs != null) { path = FileUtil.selectPath(resrcs, moduleOrFile); if (path == null) { String resrcPath = resourceDirs.toString(); throw new ToolUsageError(CeylonToolMessages.msg("error.not.in.resource.path", moduleOrFile, resrcPath)); } resFiles.add(file); // Determine the module path from the file path resMods.add(moduleName(srcs, path, file)); } } } else { visitModuleFiles(srcFiles, srcs, moduleOrFile, sourceSuffixes); srcMods.add(moduleOrFile); if (resrcs != null) { visitModuleFiles(resFiles, resrcs, moduleOrFile, null); resMods.add(moduleOrFile); } } } // Now expand the sources of any single source modules we encountered for (String modName : singleFileMods) { visitModuleFiles(srcFiles, srcs, modName, sourceSuffixes); } srcModules = new ArrayList<String>(srcMods); resModules = new ArrayList<String>(resMods); } private void visitModuleFiles(List<File> files, Iterable<File> paths, String modName, String[] suffixes) throws IOException { if (ModuleUtil.isDefaultModule(modName)) { visitFiles(paths, null, new RootedFileVisitor(files, true, suffixes)); } else { File modPath = ModuleUtil.moduleToPath(modName); if (isModuleFolder(modPath)) { visitFiles(paths, modPath, new RootedFileVisitor(files, false, suffixes)); } else { File dir = searchModulePath(modPath); if (dir == null || !dir.isDirectory()) { String ps = sourceDirs.toString(); ps = ps.substring(1, ps.length() - 1); throw new ToolUsageError(CeylonToolMessages.msg("error.module.not.found", modName, ps)); } else { throw new ToolUsageError(CeylonToolMessages.msg("error.not.module", modName)); } } } } private static void visitFiles(Iterable<File> dirs, File modPath, RootedFileVisitor visitor) throws IOException { for (File dir : dirs) { visitFiles(dir, modPath, visitor); } } private static void visitFiles(File dir, File modPath, RootedFileVisitor visitor) throws IOException { File moduleDir = dir; if (modPath != null) { moduleDir = new File(dir, modPath.getPath()); } visitor.rootPath = dir; if (moduleDir.isDirectory()) { Files.walkFileTree(moduleDir.toPath(), visitor); } } private class RootedFileVisitor extends SimpleFileVisitor<Path> { private final List<File> result; private final boolean excludeModules; private final String[] acceptedSuffixes; public File rootPath; public RootedFileVisitor(List<File> result, boolean excludeModules, String[] acceptedFiles) { this.result = result; this.excludeModules = excludeModules; this.acceptedSuffixes = acceptedFiles; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (excludeModules && isModuleFolder(rootPath, dir.toFile())) { return FileVisitResult.SKIP_SUBTREE; } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { boolean add = true; if (acceptedSuffixes != null) { add = hasAcceptedSuffix(file.toFile(), acceptedSuffixes); } if (add) { result.add(file.toFile()); } return super.visitFile(file, attrs); } } private static boolean hasAcceptedSuffix(File file, String... suffixes) { for (String ext : suffixes) { if (file.toString().endsWith(ext)) { return true; } } return false; } private boolean isModuleFolder(File rootPath, File modPath) { File relPath = FileUtil.relativeFile(rootPath, modPath); return isModuleFolder(relPath); } private boolean isModuleFolder(File modPath) { Iterable<File> srcs = FileUtil.applyCwd(cwd, sourceDirs); return ModuleUtil.isModuleFolder(srcs, modPath); } private File searchModulePath(File modPath) { Iterable<File> srcs = FileUtil.applyCwd(cwd, sourceDirs); return FileUtil.searchPaths(srcs, modPath.getPath()); } private String moduleName(Iterable<File> srcs, File rootPath, File file) { File relFile = FileUtil.relativeFile(rootPath, file); return ModuleUtil.moduleName(srcs, relFile); } }
package gl3.helloTexture; import com.jogamp.nativewindow.util.Dimension; import com.jogamp.newt.Display; import com.jogamp.newt.NewtFactory; import com.jogamp.newt.Screen; import com.jogamp.newt.event.KeyEvent; import com.jogamp.newt.event.KeyListener; import com.jogamp.newt.opengl.GLWindow; import com.jogamp.opengl.GL; import static com.jogamp.opengl.GL.GL_INVALID_ENUM; import static com.jogamp.opengl.GL.GL_INVALID_FRAMEBUFFER_OPERATION; import static com.jogamp.opengl.GL.GL_INVALID_OPERATION; import static com.jogamp.opengl.GL.GL_INVALID_VALUE; import static com.jogamp.opengl.GL.GL_NO_ERROR; import static com.jogamp.opengl.GL.GL_OUT_OF_MEMORY; import static com.jogamp.opengl.GL2ES2.GL_FRAGMENT_SHADER; import static com.jogamp.opengl.GL2ES2.GL_VERTEX_SHADER; import com.jogamp.opengl.GL4; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLCapabilities; import com.jogamp.opengl.GLEventListener; import com.jogamp.opengl.GLProfile; import com.jogamp.opengl.math.FloatUtil; import com.jogamp.opengl.util.Animator; import com.jogamp.opengl.util.GLBuffers; import com.jogamp.opengl.util.glsl.ShaderCode; import com.jogamp.opengl.util.glsl.ShaderProgram; import com.jogamp.opengl.util.texture.TextureData; import com.jogamp.opengl.util.texture.TextureIO; import framework.BufferUtils; import framework.Semantic; import java.io.File; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author gbarbieri */ public class HelloTexture implements GLEventListener, KeyListener { private static int screenIdx = 0; private static Dimension windowSize = new Dimension(1024, 768); private static boolean undecorated = false; private static boolean alwaysOnTop = false; private static boolean fullscreen = false; private static boolean mouseVisible = true; private static boolean mouseConfined = false; private static String title = "Hello Texture"; public static GLWindow glWindow; public static Animator animator; public static void main(String[] args) { Display display = NewtFactory.createDisplay(null); Screen screen = NewtFactory.createScreen(display, screenIdx); GLProfile glProfile = GLProfile.get(GLProfile.GL4); GLCapabilities glCapabilities = new GLCapabilities(glProfile); glWindow = GLWindow.create(screen, glCapabilities); glWindow.setSize(windowSize.getWidth(), windowSize.getHeight()); glWindow.setPosition(50, 50); glWindow.setUndecorated(undecorated); glWindow.setAlwaysOnTop(alwaysOnTop); glWindow.setFullscreen(fullscreen); glWindow.setPointerVisible(mouseVisible); glWindow.confinePointer(mouseConfined); glWindow.setTitle(title); glWindow.setVisible(true); HelloTexture helloTexture = new HelloTexture(); glWindow.addGLEventListener(helloTexture); glWindow.addKeyListener(helloTexture); animator = new Animator(glWindow); animator.start(); } private int[] objects = new int[Semantic.Object.SIZE]; // Position interleaved with texture coordinate. private float[] vertexData = new float[]{ -0.5f, -0.5f, 0f, 0f, -0.5f, +0.5f, 0f, 1f, +0.5f, +0.5f, 1f, 1f, +0.5f, -0.5f, 1f, 0f }; private short[] indexData = new short[]{ 0, 1, 3, 1, 2, 3 }; private int program, modelToClipMatrixUL, texture0UL; private final String SHADERS_ROOT = "src/gl3/helloTexture/shaders"; private final String TEXTURE_ROOT = "src/gl3/helloTexture/asset"; private final String TEXTURE_NAME = "texture.png"; /** * Use pools, you don't want to create and let them cleaned by the garbage * collector continuosly in the display() method. */ private float[] zRotazion = new float[16]; private long start, now; public HelloTexture() { } @Override public void init(GLAutoDrawable drawable) { System.out.println("init"); GL4 gl4 = drawable.getGL().getGL4(); initVbo(gl4); initIbo(gl4); initVao(gl4); initTexture(gl4); initSampler(gl4); initProgram(gl4); gl4.glEnable(GL4.GL_DEPTH_TEST); start = System.currentTimeMillis(); } private void initVbo(GL4 gl4) { gl4.glGenBuffers(1, objects, Semantic.Object.VBO); gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, objects[Semantic.Object.VBO]); { FloatBuffer vertexBuffer = GLBuffers.newDirectFloatBuffer(vertexData); int size = vertexData.length * Float.BYTES; gl4.glBufferData(GL4.GL_ARRAY_BUFFER, size, vertexBuffer, GL4.GL_STATIC_DRAW); /** * Since vertexBuffer is a direct buffer, this means it is outside * the Garbage Collector job and it is up to us to remove it. */ BufferUtils.destroyDirectBuffer(vertexBuffer); } gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); checkError(gl4, "initVbo"); } private void initIbo(GL4 gl4) { gl4.glGenBuffers(1, objects, Semantic.Object.IBO); gl4.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, objects[Semantic.Object.IBO]); { ShortBuffer indexBuffer = GLBuffers.newDirectShortBuffer(indexData); int size = indexData.length * Short.BYTES; gl4.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, size, indexBuffer, GL4.GL_STATIC_DRAW); BufferUtils.destroyDirectBuffer(indexBuffer); } gl4.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0); checkError(gl4, "initIbo"); } private void initVao(GL4 gl4) { /** * Let's create the VAO and save in it all the attributes properties. */ gl4.glGenVertexArrays(1, objects, Semantic.Object.VAO); gl4.glBindVertexArray(objects[Semantic.Object.VAO]); { /** * Ibo is part of the VAO, so we need to bind it and leave it bound. */ gl4.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, objects[Semantic.Object.IBO]); { /** * VBO is not part of VAO, we need it to bind it only when we * call glEnableVertexAttribArray and glVertexAttribPointer, so * that VAO knows which VBO the attributes refer to, then we can * unbind it. */ gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, objects[Semantic.Object.VBO]); { int stride = (2 + 2) * Float.BYTES; /** * We draw in 2D on the xy plane, so we need just two * coordinates for the position, it will be padded to vec4 * as (x, y, 0, 1) in the vertex shader. */ gl4.glEnableVertexAttribArray(Semantic.Attr.POSITION); gl4.glVertexAttribPointer(Semantic.Attr.POSITION, 2, GL4.GL_FLOAT, false, stride, 0 * Float.BYTES); /** * 2D Texture coordinates. */ gl4.glEnableVertexAttribArray(Semantic.Attr.TEXCOORD); gl4.glVertexAttribPointer(Semantic.Attr.TEXCOORD, 2, GL4.GL_FLOAT, false, stride, 2 * Float.BYTES); } gl4.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); } } gl4.glBindVertexArray(0); checkError(gl4, "initVao"); } private void initTexture(GL4 gl4) { try { File textureFile = new File(TEXTURE_ROOT + "/" + TEXTURE_NAME); /** * Texture data is an object containing all the relevant information * about texture. */ TextureData textureData = TextureIO.newTextureData(gl4.getGLProfile(), textureFile, false, TextureIO.PNG); /** * We don't use multiple levels (mipmaps) here, then our maximum * level is zero. */ int level = 0; gl4.glGenTextures(1, objects, Semantic.Object.TEXTURE); gl4.glBindTexture(GL4.GL_TEXTURE_2D, objects[Semantic.Object.TEXTURE]); { /** * In this example internal format is GL_RGB8, dimensions are * 512 x 512, border should always be zero, pixelFormat GL_RGB, * pixelType GL_UNSIGNED_BYTE. */ gl4.glTexImage2D(GL4.GL_TEXTURE_2D, level, textureData.getInternalFormat(), textureData.getWidth(), textureData.getHeight(), textureData.getBorder(), textureData.getPixelFormat(), textureData.getPixelType(), textureData.getBuffer()); /** * We set the base and max level. */ gl4.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_BASE_LEVEL, 0); gl4.glTexParameteri(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_MAX_LEVEL, level); /** * We set the swizzling. Since it is an RGB texture, we can * choose to make the missing component alpha equal to one. */ int[] swizzle = new int[]{GL4.GL_RED, GL4.GL_GREEN, GL4.GL_BLUE, GL4.GL_ONE}; gl4.glTexParameterIiv(GL4.GL_TEXTURE_2D, GL4.GL_TEXTURE_SWIZZLE_RGBA, swizzle, 0); } gl4.glBindTexture(GL4.GL_TEXTURE_2D, 0); } catch (IOException ex) { Logger.getLogger(HelloTexture.class.getName()).log(Level.SEVERE, null, ex); } } private void initSampler(GL4 gl4) { /** * As with most OpenGL objects, we create a sampler object with * glGenSamplers. However, notice something unusual with the next series * of functions. We do not bind a sampler to the context to set * parameters in it, nor does glSamplerParameter take a context target. * We simply pass an object directly to the function. */ gl4.glGenSamplers(1, objects, Semantic.Object.SAMPLER); gl4.glSamplerParameteri(objects[Semantic.Object.SAMPLER], GL4.GL_TEXTURE_MAG_FILTER, GL4.GL_NEAREST); gl4.glSamplerParameteri(objects[Semantic.Object.SAMPLER], GL4.GL_TEXTURE_MIN_FILTER, GL4.GL_NEAREST); gl4.glSamplerParameteri(objects[Semantic.Object.SAMPLER], GL4.GL_TEXTURE_WRAP_S, GL4.GL_CLAMP_TO_EDGE); gl4.glSamplerParameteri(objects[Semantic.Object.SAMPLER], GL4.GL_TEXTURE_WRAP_T, GL4.GL_CLAMP_TO_EDGE); } private void initProgram(GL4 gl4) { ShaderCode vertShader = ShaderCode.create(gl4, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT, null, "vs", "glsl", null, true); ShaderCode fragShader = ShaderCode.create(gl4, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT, null, "fs", "glsl", null, true); ShaderProgram shaderProgram = new ShaderProgram(); shaderProgram.add(vertShader); shaderProgram.add(fragShader); shaderProgram.init(gl4); program = shaderProgram.program(); /** * These links don't go into effect until you link the program. If you * want to change index, you need to link the program again. */ gl4.glBindAttribLocation(program, Semantic.Attr.POSITION, "position"); gl4.glBindAttribLocation(program, Semantic.Attr.TEXCOORD, "texCoord"); gl4.glBindFragDataLocation(program, Semantic.Frag.COLOR, "outputColor"); shaderProgram.link(gl4, System.out); /** * Take in account that JOGL offers a GLUniformData class, here we don't * use it, but take a look to it since it may be interesting for you. */ modelToClipMatrixUL = gl4.glGetUniformLocation(program, "modelToClipMatrix"); texture0UL = gl4.glGetUniformLocation(program, "texture0"); gl4.glUseProgram(program); { /** * We bind the uniform texture0UL to the Texture Image Units zero * or, in other words, Semantic.Uniform.TEXTURE0. */ gl4.glUniform1i(texture0UL, Semantic.Sampler.DIFFUSE); } gl4.glUseProgram(0); checkError(gl4, "initProgram"); } @Override public void dispose(GLAutoDrawable drawable) { System.out.println("dispose"); GL4 gl4 = drawable.getGL().getGL4(); gl4.glDeleteProgram(program); /** * Clean VAO first in order to minimize problems. If you delete IBO * first, VAO will still have the IBO id, this may lead to crashes. */ gl4.glDeleteVertexArrays(1, objects, objects[Semantic.Object.VAO]); gl4.glDeleteBuffers(1, objects, Semantic.Object.VBO); gl4.glDeleteBuffers(1, objects, Semantic.Object.IBO); gl4.glDeleteTextures(1, objects, Semantic.Object.TEXTURE); System.exit(0); } @Override public void display(GLAutoDrawable drawable) { // System.out.println("display"); GL4 gl4 = drawable.getGL().getGL4(); /** * We set the clear color and depth (althought depth is not necessary * since it is 1 by default). */ gl4.glClearColor(0f, .33f, 0.66f, 1f); gl4.glClearDepthf(1f); gl4.glClear(GL4.GL_COLOR_BUFFER_BIT | GL4.GL_DEPTH_BUFFER_BIT); gl4.glUseProgram(program); { gl4.glBindVertexArray(objects[Semantic.Object.VAO]); { now = System.currentTimeMillis(); float diff = (float) (now - start) / 1000; /** * Here we build the matrix that will multiply our original * vertex positions. We scale, halving it, and rotate it. */ zRotazion = FloatUtil.makeRotationEuler(zRotazion, 0, 0, 0, diff); gl4.glUniformMatrix4fv(modelToClipMatrixUL, 1, false, zRotazion, 0); /** * The glActiveTexture function changes the current texture * unit. All subsequent texture operations, whether * glBindTexture, glTexImage, glTexParameter, etc, affect the * texture bound to the current texture unit. * * What this means is that if you want to modify a texture, you * must overwrite a texture unit that may already be bound. This * is usually not a huge problem, because you rarely modify * textures in the same area of code used to render. But you * should be aware of this. * * Also note the peculiar glActiveTexture syntax for specifying * the image unit: GL_TEXTURE0 + Semantic.Uniform.TEXTURE0. This * is the correct way to specify which texture unit, because * glActiveTexture is defined in terms of an enumerator rather * than integer texture image units. */ gl4.glActiveTexture(GL4.GL_TEXTURE0 + Semantic.Sampler.DIFFUSE); gl4.glBindTexture(GL4.GL_TEXTURE_2D, objects[Semantic.Object.TEXTURE]); { gl4.glBindSampler(Semantic.Sampler.DIFFUSE, objects[Semantic.Object.SAMPLER]); { gl4.glDrawElements(GL4.GL_TRIANGLES, indexData.length, GL4.GL_UNSIGNED_SHORT, 0); } gl4.glBindSampler(Semantic.Sampler.DIFFUSE, 0); } gl4.glBindTexture(GL4.GL_TEXTURE_2D, 0); } /** * In this sample we bind VAO to the default values, this is not a * cheapier binding, it costs always as a binding, so here we have * for example 2 vao bindings. Every binding means additional * validation and overhead, this may affect your performances. So if * you are looking for high performances skip these calls, but * remember that OpenGL is a state machine, so what you left bound * remains bound! */ gl4.glBindVertexArray(0); } gl4.glUseProgram(0); /** * Check always any GL error, but keep in mind this is an implicit * synchronization between CPU and GPU, so you should use it only for * debug purposes. */ checkError(gl4, "display"); } protected boolean checkError(GL gl, String title) { int error = gl.glGetError(); if (error != GL_NO_ERROR) { String errorString; switch (error) { case GL_INVALID_ENUM: errorString = "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: errorString = "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: errorString = "GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: errorString = "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: errorString = "GL_OUT_OF_MEMORY"; break; default: errorString = "UNKNOWN"; break; } System.out.println("OpenGL Error(" + errorString + "): " + title); throw new Error(); } return error == GL_NO_ERROR; } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { System.out.println("reshape"); GL4 gl4 = drawable.getGL().getGL4(); /** * Just the glViewport for this sample, normally here you update your * projection matrix. */ gl4.glViewport(x, y, width, height); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { HelloTexture.animator.stop(); } } @Override public void keyReleased(KeyEvent e) { } }
package org.pdxfinder.postload; import org.apache.commons.collections4.map.HashedMap; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.pdxfinder.BaseTest; import org.pdxfinder.services.DataImportService; import org.pdxfinder.services.DrugService; import org.springframework.boot.test.mock.mockito.MockBean; import static org.mockito.Mockito.*; import java.util.*; public class DataProjectionTest extends BaseTest { CreateDataProjections createDataProjections; @MockBean DataImportService dataImportService; @MockBean DrugService drugService; @Before public void init() { createDataProjections = new CreateDataProjections(dataImportService, drugService); } @Test public void given_HashMapDP_when_saveDP_then_Saved(){ createDataProjections.setCytogeneticsDP(getTwoKeyData()); createDataProjections.setMutatedPlatformMarkerVariantModelDP(getThreeKeyData()); createDataProjections.setModelDrugResponseDP(getTwoKeyData()); createDataProjections.setImmunoHistoChemistryDP(getTwoKeyData()); createDataProjections.setCopyNumberAlterationDP(getOneKeyData()); createDataProjections.setExpressionDP(getTwoKeyData()); createDataProjections.setDrugDosingDP(getOneKeyData()); createDataProjections.setPatientTreatmentDP(getOneKeyData()); createDataProjections.setFrequentlyMutatedMarkersDP(new ArrayList<>()); createDataProjections.setExpressionDP(getTwoKeyData()); createDataProjections.setDataAvailableDP(new HashedMap<>()); createDataProjections.setFrequentlyMutatedMarkersDP(new ArrayList<>()); when(dataImportService.saveDataProjection(any())).thenAnswer(i -> i.getArguments()[0]); when(dataImportService.findDataProjectionByLabel(any())).thenReturn(null); createDataProjections.saveDataProjections(); Assert.assertEquals("cytogenetics", createDataProjections.saveDP("cytogenetics", createDataProjections.getCytogeneticsDP()).getLabel()); Assert.assertEquals("copy number alteration", createDataProjections.saveDP("copy number alteration", createDataProjections.getCopyNumberAlterationDP()).getLabel()); Assert.assertEquals("expression", createDataProjections.saveDP("expression", createDataProjections.getExpressionDP()).getLabel()); Assert.assertEquals("PlatformMarkerVariantModel", createDataProjections.saveDP("PlatformMarkerVariantModel", createDataProjections.getMutatedPlatformMarkerVariantModelDP()).getLabel()); Assert.assertEquals("ModelDrugData", createDataProjections.saveDP("ModelDrugData", createDataProjections.getModelDrugResponseDP()).getLabel()); Assert.assertEquals("breast cancer markers", createDataProjections.saveDP("breast cancer markers", createDataProjections.getImmunoHistoChemistryDP()).getLabel()); Assert.assertEquals("drug dosing counter", createDataProjections.saveDP("drug dosing counter", createDataProjections.getDrugDosingDP()).getLabel()); Assert.assertEquals("patient treatment", createDataProjections.saveDP("patient treatment", createDataProjections.getPatientTreatmentDP()).getLabel()); Assert.assertEquals("MarkerVariant", createDataProjections.saveDP("MarkerVariant", createDataProjections.getMutatedMarkerVariantDP()).getLabel()); Assert.assertEquals("data available", createDataProjections.saveDP("data available", createDataProjections.getDataAvailableDP()).getLabel()); Assert.assertEquals("frequently mutated genes", createDataProjections.saveDP("frequently mutated genes", createDataProjections.getFrequentlyMutatedMarkersDP()).getLabel()); } @Test public void given_Json_when_jsonKeyIsNull_then_ExceptionIsThrown(){ Map<String, Long> map = new HashedMap<>(); map.put(null, new Long(1)); Assert.assertEquals("", createDataProjections.createJsonString(map)); } private Map<String, Set<Long>> getOneKeyData(){ Set<Long> modelIds = new HashSet<>(); modelIds.add(new Long(1)); Map<String, Set<Long>> map1 = new HashMap<>(); map1.put("key1", modelIds); return map1; } private Map<String, Map<String, Set<Long>>> getTwoKeyData(){ Set<Long> modelIds = new HashSet<>(); modelIds.add(new Long(1)); Map<String, Set<Long>> map2 = new HashMap<>(); Map<String, Map<String, Set<Long>>> map1 = new HashMap<>(); map2.put("key2", modelIds); map1.put("key1", map2); return map1; } private Map<String, Map<String, Map<String, Set<Long>>>> getThreeKeyData(){ Set<Long> modelIds = new HashSet<>(); modelIds.add(new Long(1)); Map<String, Set<Long>> map3 = new HashMap<>(); Map<String, Map<String, Set<Long>>> map2 = new HashMap<>(); Map<String, Map<String, Map<String, Set<Long>>>> map1 = new HashMap<>(); map3.put("key3",modelIds); map2.put("key2", map3); map1.put("key1", map2); return map1; } }
package ValkyrienWarfareBase; import java.io.File; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import ValkyrienWarfareBase.API.DataTag; import ValkyrienWarfareBase.API.ValkyrienWarfareHooks; import ValkyrienWarfareBase.API.Vector; import ValkyrienWarfareBase.Block.BlockPhysicsInfuser; import ValkyrienWarfareBase.Block.BlockPhysicsInfuserCreative; import ValkyrienWarfareBase.ChunkManagement.DimensionPhysicsChunkManager; import ValkyrienWarfareBase.PhysicsManagement.DimensionPhysObjectManager; import ValkyrienWarfareBase.PhysicsManagement.PhysicsWrapperEntity; import ValkyrienWarfareBase.PhysicsManagement.Network.PhysWrapperPositionHandler; import ValkyrienWarfareBase.PhysicsManagement.Network.PhysWrapperPositionMessage; import ValkyrienWarfareBase.Proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartedEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; import net.minecraftforge.fml.common.event.FMLStateEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; @Mod(modid = ValkyrienWarfareMod.MODID, name = ValkyrienWarfareMod.MODNAME, version = ValkyrienWarfareMod.MODVER, guiFactory = "ValkyrienWarfareBase.GUI.GuiFactoryValkyrienWarfare", updateJSON = "https://raw.githubusercontent.com/BigBastard/Valkyrien-Warfare-Revamped/update.json") public class ValkyrienWarfareMod { @SidedProxy(clientSide = "ValkyrienWarfareBase.Proxy.ClientProxy", serverSide = "ValkyrienWarfareBase.Proxy.ServerProxy") public static CommonProxy proxy; public static final String MODID = "valkyrienwarfare"; public static final String MODNAME = "Valkyrien Warfare"; public static final String MODVER = "0.86d"; public static File configFile; public static Configuration config; public static boolean dynamicLighting, spawnParticles; public static int shipTickDelay, maxMissedPackets; public static int threadCount; public static boolean multiThreadedPhysics; public static boolean doSplitting = false; public static boolean doShipCollision = false; public static Vector gravity = new Vector(0, -9.8D, 0); public static int physIter = 10; public static double physSpeed = .05D; public static Block physicsInfuser; public static Block physicsInfuserCreative; public static SimpleNetworkWrapper physWrapperNetwork; public static DimensionPhysicsChunkManager chunkManager; public static DimensionPhysObjectManager physicsManager; public static ValkyrienWarfareMod instance; public static int airStateIndex; public static double standingTolerance = .42D; public static int maxShipSize = 15000; public static double shipUpperLimit = 1000D; public static double shipLowerLimit = -30D; // NOTE: These only calculate physics, so they are only relevant to the Server end public static ExecutorService MultiThreadExecutor; public DataTag tag = null; @EventHandler public void preInit(FMLPreInitializationEvent event) { proxy.preInit(event); instance = this; registerBlocks(event); registerRecipies(event); registerNetworks(event); runConfiguration(event); ValkyrienWarfareHooks.methods = new RealMethods(); ValkyrienWarfareHooks.isValkyrienWarfareInstalled = true; } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); EntityRegistry.registerModEntity(PhysicsWrapperEntity.class, "PhysWrapper", 70, this, 120, 1, false); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); airStateIndex = Block.getStateId(Blocks.AIR.getDefaultState()); BlockPhysicsRegistration.registerCustomBlockMasses(); BlockPhysicsRegistration.registerVanillaBlockForces(); } @EventHandler public void serverStart(FMLServerStartingEvent event) { MinecraftServer server = event.getServer(); ExtraRegistry.registerCommands(server); } private void registerNetworks(FMLStateEvent event) { physWrapperNetwork = NetworkRegistry.INSTANCE.newSimpleChannel("physChannel"); physWrapperNetwork.registerMessage(PhysWrapperPositionHandler.class, PhysWrapperPositionMessage.class, 0, Side.CLIENT); } private void registerBlocks(FMLStateEvent event) { physicsInfuser = new BlockPhysicsInfuser(Material.ROCK).setHardness(12f).setUnlocalizedName("shipblock").setRegistryName(MODID, "shipblock").setCreativeTab(CreativeTabs.TRANSPORTATION); physicsInfuserCreative = new BlockPhysicsInfuserCreative(Material.ROCK).setHardness(12f).setUnlocalizedName("shipblockcreative").setRegistryName(MODID, "shipblockcreative").setCreativeTab(CreativeTabs.TRANSPORTATION); ; GameRegistry.registerBlock(physicsInfuser); GameRegistry.registerBlock(physicsInfuserCreative); } private void registerRecipies(FMLStateEvent event) { GameRegistry.addRecipe(new ItemStack(physicsInfuser), new Object[] { "RRR", "RDR", "RRR", 'R', Items.REDSTONE, 'D', Item.getItemFromBlock(Blocks.DIAMOND_BLOCK) }); } private void runConfiguration(FMLPreInitializationEvent event) { configFile = event.getSuggestedConfigurationFile(); config = new Configuration(configFile); config.load(); applyConfig(config); config.save(); } public static void applyConfig(Configuration conf) { // Property dynamiclightProperty = config.get(Configuration.CATEGORY_GENERAL, "DynamicLighting", false); Property shipTickDelayProperty = config.get(Configuration.CATEGORY_GENERAL, "Ticks Delay Between Client and Server", 1); Property missedPacketsTolerance = config.get(Configuration.CATEGORY_GENERAL, "Missed packets threshold", 1); // Property spawnParticlesParticle = config.get(Configuration.CATEGORY_GENERAL, "Ships spawn particles", false); Property useMultiThreadedPhysics = config.get(Configuration.CATEGORY_GENERAL, "Multi-Threaded Physics", false); Property physicsThreads = config.get(Configuration.CATEGORY_GENERAL, "Physics Thread Count", (int) Math.max(1, Runtime.getRuntime().availableProcessors() - 2)); Property doShipCollisionProperty = config.get(Configuration.CATEGORY_GENERAL, "Enable Ship Collision", false); Property shipUpperHeightLimit = config.get(Configuration.CATEGORY_GENERAL, "Ship Y-Height Maximum", 1000D); Property shipLowerHeightLimit = config.get(Configuration.CATEGORY_GENERAL, "Ship Y-Height Minimum", -30D); // dynamiclightProperty.setComment("Dynamic Lighting"); shipTickDelayProperty.setComment("Tick delay between client and server physics; raise if physics look choppy"); missedPacketsTolerance.setComment("Higher values gaurantee virutally no choppyness, but also comes with a large delay. Only change if you have unstable internet"); // spawnParticlesParticle.setComment("Ships spawn particles"); useMultiThreadedPhysics.setComment("Use Multi-Threaded Physics"); physicsThreads.setComment("Number of threads to run physics on;"); // dynamicLighting = dynamiclightProperty.getBoolean(); shipTickDelay = shipTickDelayProperty.getInt() % 20; maxMissedPackets = missedPacketsTolerance.getInt(); // spawnParticles = spawnParticlesParticle.getBoolean(); multiThreadedPhysics = useMultiThreadedPhysics.getBoolean(); threadCount = physicsThreads.getInt(); doShipCollision = doShipCollisionProperty.getBoolean(); shipUpperLimit = shipUpperHeightLimit.getDouble(); shipLowerLimit = shipLowerHeightLimit.getDouble(); if (MultiThreadExecutor != null) { MultiThreadExecutor.shutdown(); } if (multiThreadedPhysics) { MultiThreadExecutor = Executors.newFixedThreadPool(threadCount); } } @EventHandler public void onServerStarted(FMLServerStartedEvent event) { this.loadConfig(); } @EventHandler public void onServerStopping(FMLServerStoppingEvent event) { this.saveConfig(); } public void loadConfig() { File file = new File(ValkyrienWarfareMod.getWorkingFolder(), "/valkyrienwarfaresettings.dat"); if (!file.exists()) { tag = new DataTag(file); tag.setBoolean("doGravity", true); tag.setBoolean("doPhysicsBlocks", true); tag.setBoolean("doBalloons", true); tag.setBoolean("doAirshipRotation", true); tag.setBoolean("doAirshipMovement", true); tag.setBoolean("doSplitting", false); tag.setInteger("maxShipSize", 15000); tag.setDouble("gravityVecX", 0); tag.setDouble("gravityVecY", -9.8); tag.setDouble("gravityVecZ", 0); tag.setInteger("physicsIterations", 10); tag.setDouble("physicsSpeed", 0.05); tag.save(); } else { tag = new DataTag(file); } PhysicsSettings.doGravity = tag.getBoolean("doGravity", true); PhysicsSettings.doPhysicsBlocks = tag.getBoolean("doPhysicsBlocks", true); PhysicsSettings.doBalloons = tag.getBoolean("doBalloons", true); PhysicsSettings.doAirshipRotation = tag.getBoolean("doAirshipRotation", true); PhysicsSettings.doAirshipMovement = tag.getBoolean("doAirshipMovement", true); ValkyrienWarfareMod.doSplitting = tag.getBoolean("doSplitting", false); ValkyrienWarfareMod.maxShipSize = tag.getInteger("maxShipSize", 15000); ValkyrienWarfareMod.physIter = tag.getInteger("physicsIterations", 10); ValkyrienWarfareMod.physSpeed = tag.getDouble("physicsSpeed", 0.05); ValkyrienWarfareMod.gravity = new Vector(tag.getDouble("gravityVecX", 0.0), tag.getDouble("gravityVecY", -9.8), tag.getDouble("gravityVecZ", 0.0)); } public void saveConfig() { tag.setBoolean("doGravity", PhysicsSettings.doGravity); tag.setBoolean("doPhysicsBlocks", PhysicsSettings.doPhysicsBlocks); tag.setBoolean("doBalloons", PhysicsSettings.doBalloons); tag.setBoolean("doAirshipRotation", PhysicsSettings.doAirshipRotation); tag.setBoolean("doAirshipMovement", PhysicsSettings.doAirshipMovement); tag.setBoolean("doSplitting", ValkyrienWarfareMod.doSplitting); tag.setInteger("maxShipSize", ValkyrienWarfareMod.maxShipSize); tag.setDouble("gravityVecX", ValkyrienWarfareMod.gravity.X); tag.setDouble("gravityVecY", ValkyrienWarfareMod.gravity.Y); tag.setDouble("gravityVecZ", ValkyrienWarfareMod.gravity.Z); tag.setInteger("physicsIterations", ValkyrienWarfareMod.physIter); tag.setDouble("physicsSpeed", ValkyrienWarfareMod.physSpeed); tag.save(); } public static File getWorkingFolder() { File toBeReturned; try { if (FMLCommonHandler.instance().getSide().isClient()) { toBeReturned = Minecraft.getMinecraft().mcDataDir; } else { toBeReturned = FMLCommonHandler.instance().getMinecraftServerInstance().getFile(""); } return toBeReturned; } catch (Exception e) { e.printStackTrace(); } return null; } }
package at.ac.tuwien.kr.alpha.solver; import at.ac.tuwien.kr.alpha.common.AnswerSet; import at.ac.tuwien.kr.alpha.common.NoGood; import at.ac.tuwien.kr.alpha.grounder.Grounder; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.function.Consumer; import static at.ac.tuwien.kr.alpha.common.Literals.atomOf; import static at.ac.tuwien.kr.alpha.common.Literals.isNegated; import static at.ac.tuwien.kr.alpha.solver.ThriceTruth.FALSE; import static at.ac.tuwien.kr.alpha.solver.ThriceTruth.TRUE; import static java.lang.Math.abs; public class NaiveSolver extends AbstractSolver { private static final Logger LOGGER = LoggerFactory.getLogger(NaiveSolver.class); private final ChoiceStack choiceStack; private HashMap<Integer, Boolean> truthAssignments = new HashMap<>(); private ArrayList<Integer> newTruthAssignments = new ArrayList<>(); private ArrayList<ArrayList<Integer>> decisionLevels = new ArrayList<>(); private HashMap<Integer, NoGood> knownNoGoods = new HashMap<>(); private boolean doInit = true; private boolean didChange; private int decisionLevel; private Map<Integer, Integer> choiceOn = new HashMap<>(); private Map<Integer, Integer> choiceOff = new HashMap<>(); private Integer nextChoice; private HashSet<Integer> mbtAssigned = new HashSet<>(); private ArrayList<ArrayList<Integer>> mbtAssignedFromUnassigned = new ArrayList<>(); private ArrayList<ArrayList<Integer>> trueAssignedFromMbt = new ArrayList<>(); private List<Integer> unassignedAtoms; NaiveSolver(Grounder grounder) { super(grounder); this.choiceStack = new ChoiceStack(grounder); decisionLevels.add(0, new ArrayList<>()); mbtAssignedFromUnassigned.add(0, new ArrayList<>()); trueAssignedFromMbt.add(0, new ArrayList<>()); } @Override protected boolean tryAdvance(Consumer<? super AnswerSet> action) { // Get basic rules and facts from grounder if (doInit) { obtainNoGoodsFromGrounder(); doInit = false; } else { // We already found one Answer-Set and are requested to find another one doBacktrack(); if (isSearchSpaceExhausted()) { return false; } } // Try all assignments until grounder reports no more NoGoods and all of them are satisfied while (true) { if (!propagationFixpointReached()) { LOGGER.trace("Propagating."); updateGrounderAssignments(); // After a choice, it would be more efficient to propagate first and only then ask the grounder. obtainNoGoodsFromGrounder(); doUnitPropagation(); doMBTPropagation(); LOGGER.trace("Assignment after propagation is: {}", truthAssignments); } else if (assignmentViolatesNoGoods()) { LOGGER.trace("Backtracking from wrong choices:"); LOGGER.trace("Choice stack: {}", choiceStack); doBacktrack(); if (isSearchSpaceExhausted()) { return false; } } else if (choicesLeft()) { doChoice(); } else if (!allAtomsAssigned()) { LOGGER.trace("Closing unassigned known atoms (assigning FALSE)."); assignUnassignedToFalse(); didChange = true; } else if (noMBTValuesReamining()) { AnswerSet as = getAnswerSetFromAssignment(); LOGGER.debug("Answer-Set found: {}", as); LOGGER.trace("Choice stack: {}", choiceStack); action.accept(as); return true; } else { LOGGER.debug("Backtracking from wrong choices (MBT remaining):"); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Currently MBT:"); for (Integer integer : mbtAssigned) { LOGGER.trace(grounder.atomToString(integer)); } LOGGER.trace("Choice stack: {}", choiceStack); } doBacktrack(); if (isSearchSpaceExhausted()) { return false; } } } } private void assignUnassignedToFalse() { for (Integer atom : unassignedAtoms) { truthAssignments.put(atom, false); newTruthAssignments.add(atom); decisionLevels.get(decisionLevel).add(atom); } } private boolean allAtomsAssigned() { unassignedAtoms = new ArrayList<>(); HashSet<Integer> knownAtoms = new HashSet<>(); for (Map.Entry<Integer, NoGood> entry : knownNoGoods.entrySet()) { for (Integer integer : entry.getValue()) { knownAtoms.add(abs(integer)); } } for (Integer atom : knownAtoms) { if (!truthAssignments.containsKey(atom)) { unassignedAtoms.add(atom); } } return unassignedAtoms.isEmpty(); } private boolean noMBTValuesReamining() { return mbtAssigned.size() == 0; } private void doMBTPropagation() { boolean didPropagate = true; while (didPropagate) { didPropagate = false; for (Map.Entry<Integer, NoGood> noGoodEntry : knownNoGoods.entrySet()) { if (propagateMBT(noGoodEntry.getValue())) { didPropagate = true; didChange = true; } } } } private String reportTruthAssignments() { String report = "Current Truth assignments: "; for (Integer atomId : truthAssignments.keySet()) { report += (truthAssignments.get(atomId) ? "+" : "-") + atomId + " "; } return report; } private boolean propagationFixpointReached() { // Check if anything changed. // didChange is updated in places of change. boolean changeCopy = didChange; didChange = false; return !changeCopy; } private AnswerSet getAnswerSetFromAssignment() { ArrayList<Integer> trueAtoms = new ArrayList<>(); for (Map.Entry<Integer, Boolean> atomAssignment : truthAssignments.entrySet()) { if (atomAssignment.getValue()) { trueAtoms.add(atomAssignment.getKey()); } } return translate(trueAtoms); } private void doChoice() { decisionLevel++; ArrayList<Integer> list = new ArrayList<>(); list.add(nextChoice); decisionLevels.add(decisionLevel, list); trueAssignedFromMbt.add(decisionLevel, new ArrayList<>()); mbtAssignedFromUnassigned.add(decisionLevel, new ArrayList<>()); // We guess true for any unassigned choice atom (backtrack tries false) truthAssignments.put(nextChoice, true); newTruthAssignments.add(nextChoice); choiceStack.push(nextChoice, true); // Record change to compute propagation fixpoint again. didChange = true; } private boolean choicesLeft() { // Check if there is an enabled choice that is not also disabled for (Map.Entry<Integer, Integer> e : choiceOn.entrySet()) { final int atom = e.getKey(); // Only consider unassigned choices that are enabled. if (truthAssignments.containsKey(atom) || !truthAssignments.getOrDefault(e.getValue(), false)) { continue; } // Check that candidate is not disabled already if (!truthAssignments.getOrDefault(choiceOff.getOrDefault(atom, 0), false)) { nextChoice = atom; return true; } } return false; } private void doBacktrack() { if (decisionLevel <= 0) { return; } int lastGuessedAtom = choiceStack.peekAtom(); boolean lastGuessedTruthValue = choiceStack.peekValue(); choiceStack.remove(); // Remove truth assignments of current decision level for (Integer atomId : decisionLevels.get(decisionLevel)) { truthAssignments.remove(atomId); } // Handle MBT assigned values: // First, restore mbt when it got assigned true in this decision level for (Integer atomId : trueAssignedFromMbt.get(decisionLevel)) { mbtAssigned.add(atomId); } // Second, remove mbt indicator for values that were unassigned for (Integer atomId : mbtAssignedFromUnassigned.get(decisionLevel)) { mbtAssigned.remove(atomId); } // Clear atomIds in current decision level decisionLevels.set(decisionLevel, new ArrayList<>()); mbtAssignedFromUnassigned.set(decisionLevel, new ArrayList<>()); trueAssignedFromMbt.set(decisionLevel, new ArrayList<>()); if (lastGuessedTruthValue) { // Guess false now truthAssignments.put(lastGuessedAtom, false); choiceStack.pushBacktrack(lastGuessedAtom, false); newTruthAssignments.add(lastGuessedAtom); decisionLevels.get(decisionLevel).add(lastGuessedAtom); didChange = true; } else { decisionLevel doBacktrack(); } } private void updateGrounderAssignments() { grounder.updateAssignment(newTruthAssignments.stream().map(atom -> { return (Assignment.Entry)new Entry(atom, truthAssignments.get(atom) ? TRUE : FALSE); }).iterator()); newTruthAssignments.clear(); } private static final class Entry implements Assignment.Entry { private final ThriceTruth value; private final int atom; Entry(int atom, ThriceTruth value) { this.value = value; this.atom = atom; } @Override public ThriceTruth getTruth() { return value; } @Override public int getDecisionLevel() { throw new UnsupportedOperationException(); } @Override public NoGood getImpliedBy() { throw new UnsupportedOperationException(); } @Override public Entry getPrevious() { throw new UnsupportedOperationException(); } @Override public int getAtom() { return atom; } @Override public int getPropagationLevel() { throw new UnsupportedOperationException(); } @Override public boolean isReassignAtLowerDecisionLevel() { throw new UnsupportedOperationException(); } @Override public String toString() { throw new UnsupportedOperationException(); } } private void obtainNoGoodsFromGrounder() { final int oldSize = knownNoGoods.size(); knownNoGoods.putAll(grounder.getNoGoods()); if (oldSize != knownNoGoods.size()) { // Record to detect propagation fixpoint, checking if new NoGoods were reported would be better here. didChange = true; } // Record choice atoms final Pair<Map<Integer, Integer>, Map<Integer, Integer>> choiceAtoms = grounder.getChoiceAtoms(); choiceOn.putAll(choiceAtoms.getKey()); choiceOff.putAll(choiceAtoms.getValue()); } private boolean isSearchSpaceExhausted() { return decisionLevel == 0; } private void doUnitPropagation() { // Check each NoGood if it is unit (naive algorithm) for (NoGood noGood : knownNoGoods.values()) { int implied = unitPropagate(noGood); if (implied == -1) { // NoGood is not unit, skip. continue; } int impliedLiteral = noGood.getLiteral(implied); int impliedAtomId = atomOf(impliedLiteral); boolean impliedTruthValue = isNegated(impliedLiteral); if (truthAssignments.get(impliedAtomId) != null) { // Skip if value already was assigned. continue; } truthAssignments.put(impliedAtomId, impliedTruthValue); newTruthAssignments.add(impliedAtomId); didChange = true; // Record to detect propagation fixpoint decisionLevels.get(decisionLevel).add(impliedAtomId); if (impliedTruthValue) { // Record MBT value in case true is assigned mbtAssigned.add(impliedAtomId); mbtAssignedFromUnassigned.get(decisionLevel).add(impliedAtomId); } } } private boolean isLiteralAssigned(int literal) { return truthAssignments.get(atomOf(literal)) != null; } private boolean isLiteralViolated(int literal) { final int atom = atomOf(literal); final Boolean assignment = truthAssignments.get(atom); // For unassigned atoms, any literal is not violated. return assignment != null && isNegated(literal) != assignment; } /** * Returns position of implied literal if input NoGood is unit. * @param noGood * @return -1 if NoGood is not unit. */ private int unitPropagate(NoGood noGood) { int lastUnassignedPosition = -1; for (int i = 0; i < noGood.size(); i++) { int literal = noGood.getLiteral(i); if (isLiteralAssigned(literal)) { if (!isLiteralViolated(literal)) { // The NoGood is satisfied, hence it cannot be unit. return -1; } } else if (lastUnassignedPosition != -1) { // NoGood is not unit, if there is not exactly one unassigned literal return -1; } else { lastUnassignedPosition = i; } } return lastUnassignedPosition; } private boolean propagateMBT(NoGood noGood) { // The MBT propagation checks whether the head-indicated literal is MBT // and the remaining literals are violated // and none of them are MBT, // then the head literal is set from MBT to true. if (!noGood.hasHead()) { return false; } int headAtom = noGood.getAtom(noGood.getHead()); // Check whether head is assigned MBT. if (!mbtAssigned.contains(headAtom)) { return false; } // Check that NoGood is violated except for the head (i.e., without the head set it would be unit) // and that none of the true values is MBT. for (int i = 0; i < noGood.size(); i++) { if (noGood.getHead() == i) { continue; } int literal = noGood.getLiteral(i); if (!(isLiteralAssigned(literal) && isLiteralViolated(literal))) { return false; } } // Set truth value from MBT to true. mbtAssigned.remove(headAtom); trueAssignedFromMbt.get(decisionLevel).add(headAtom); return true; } private boolean assignmentViolatesNoGoods() { // Check each NoGood, if it is violated for (NoGood noGood : knownNoGoods.values()) { boolean isSatisfied = false; for (Integer noGoodLiteral : noGood) { if (!isLiteralAssigned(noGoodLiteral) || !isLiteralViolated(noGoodLiteral)) { isSatisfied = true; break; } } if (!isSatisfied) { LOGGER.trace("Violated NoGood: {}", noGood); return true; } } return false; } }
package nerd.tuxmobil.fahrplan.congress; import nerd.tuxmobil.fahrplan.congress.CustomHttpClient.HTTP_STATUS; import nerd.tuxmobil.fahrplan.congress.MyApp.TASKS; import com.actionbarsherlock.app.SherlockDialogFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.format.Time; import android.view.View; import android.widget.FrameLayout; public class MainActivity extends SherlockFragmentActivity implements OnParseCompleteListener, OnDownloadCompleteListener, OnCloseDetailListener, OnRefreshEventMarkers, OnCertAccepted { private static final String LOG_TAG = "MainActivity"; private FetchFahrplan fetcher; private FahrplanParser parser; private ProgressDialog progress = null; private MyApp global; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApp.LogDebug(LOG_TAG, "onCreate"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main_layout); setSupportProgressBarIndeterminateVisibility(false); getSupportActionBar().setTitle(R.string.fahrplan); if (MyApp.fetcher == null) { fetcher = new FetchFahrplan(); } else { fetcher = MyApp.fetcher; } if (MyApp.parser == null) { parser = new FahrplanParser(getApplicationContext()); } else { parser = MyApp.parser; } progress = null; global = (MyApp) getApplicationContext(); FahrplanMisc.loadMeta(this); FahrplanMisc.loadDays(this); MyApp.LogDebug(LOG_TAG, "task_running:" + MyApp.task_running); switch (MyApp.task_running) { case FETCH: MyApp.LogDebug(LOG_TAG, "fetch was pending, restart"); showFetchingStatus(); break; case PARSE: MyApp.LogDebug(LOG_TAG, "parse was pending, restart"); showParsingStatus(); break; case NONE: if ((MyApp.numdays == 0) && (savedInstanceState == null)) { MyApp.LogDebug(LOG_TAG,"fetch in onCreate bc. numdays==0"); fetchFahrplan(this); } break; } if (findViewById(R.id.schedule) != null) { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("schedule") == null) { FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.schedule, new FahrplanFragment(), "schedule"); fragmentTransaction.commit(); } } if (findViewById(R.id.detail) == null) { FragmentManager fm = getSupportFragmentManager(); Fragment detail = fm.findFragmentByTag("detail"); if (detail != null) { FragmentTransaction ft = fm.beginTransaction(); ft.remove(detail).commit(); } } } public void parseFahrplan() { showParsingStatus(); MyApp.task_running = TASKS.PARSE; parser.setListener(this); parser.parse(MyApp.fahrplan_xml, MyApp.eTag); } public void onGotResponse(HTTP_STATUS status, String response, String eTagStr) { MyApp.LogDebug(LOG_TAG, "Response... " + status); MyApp.task_running = TASKS.NONE; if (MyApp.numdays == 0) { if (progress != null) { progress.dismiss(); progress = null; } } if ((status == HTTP_STATUS.HTTP_OK) || (status == HTTP_STATUS.HTTP_NOT_MODIFIED)) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Time now = new Time(); now.setToNow(); long millis = now.toMillis(true); Editor edit = prefs.edit(); edit.putLong("last_fetch", millis); edit.commit(); } if (status != HTTP_STATUS.HTTP_OK) { switch (status) { case HTTP_CANCELLED: break; case HTTP_LOGIN_FAIL_UNTRUSTED_CERTIFICATE: CertificateDialogFragment dlg = new CertificateDialogFragment(); Bundle args = new Bundle(); args.putInt("msgResId", R.string.dlg_certificate_message_fmt); dlg.show(getSupportFragmentManager(), "cert_dlg"); break; } CustomHttpClient.showHttpError(this, global, status); setSupportProgressBarIndeterminateVisibility(false); return; } MyApp.LogDebug(LOG_TAG, "yehhahh"); setSupportProgressBarIndeterminateVisibility(false); MyApp.fahrplan_xml = response; MyApp.eTag = eTagStr; parseFahrplan(); } @Override public void onParseDone(Boolean result, String version) { MyApp.LogDebug(LOG_TAG, "parseDone: " + result + " , numdays="+MyApp.numdays); MyApp.task_running = TASKS.NONE; MyApp.fahrplan_xml = null; if (MyApp.numdays == 0) { if (progress != null) { progress.dismiss(); progress = null; } } setSupportProgressBarIndeterminateVisibility(false); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentByTag("schedule"); if ((fragment != null) && (fragment instanceof OnParseCompleteListener)) { ((OnParseCompleteListener)fragment).onParseDone(result, version); } } public void showFetchingStatus() { if (MyApp.numdays == 0) { // initial load MyApp.LogDebug(LOG_TAG, "fetchFahrplan with numdays == 0"); progress = ProgressDialog.show(this, "", getResources().getString( R.string.progress_loading_data), true); } else { MyApp.LogDebug(LOG_TAG, "show fetch status"); setSupportProgressBarIndeterminateVisibility(true); } } public void showParsingStatus() { if (MyApp.numdays == 0) { // initial load progress = ProgressDialog.show(this, "", getResources().getString( R.string.progress_processing_data), true); } else { MyApp.LogDebug(LOG_TAG, "show parse status"); setSupportProgressBarIndeterminateVisibility(true); } } public void fetchFahrplan(OnDownloadCompleteListener completeListener) { if (MyApp.task_running == TASKS.NONE) { MyApp.task_running = TASKS.FETCH; showFetchingStatus(); fetcher.setListener(completeListener); fetcher.fetch(MyApp.schedulePath, MyApp.eTag); } else { MyApp.LogDebug(LOG_TAG, "fetch already in progress"); } } @Override protected void onDestroy() { super.onDestroy(); if (progress != null) { progress.dismiss(); progress = null; } } @Override protected void onPause() { if (MyApp.fetcher != null) MyApp.fetcher.setListener(null); if (MyApp.parser != null) MyApp.parser.setListener(null); super.onPause(); } @Override protected void onResume() { super.onResume(); if (MyApp.fetcher != null) MyApp.fetcher.setListener(this); if (MyApp.parser != null) MyApp.parser.setListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater mi = getSupportMenuInflater(); mi.inflate(R.menu.mainmenu, menu); return true; } void aboutDialog() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.addToBackStack(null); SherlockDialogFragment about = new AboutDialog(); about.show(ft, "about"); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.item_refresh: fetchFahrplan(this); return true; case R.id.item_about: aboutDialog(); return true; case R.id.item_alarms: intent = new Intent(this, AlarmList.class); startActivityForResult(intent, MyApp.ALARMLIST); return true; case R.id.item_settings: intent = new Intent(this, Prefs.class); startActivity(intent); return true; default: } return super.onOptionsItemSelected(item); } public void openLectureDetail(Lecture lecture, int mDay) { FrameLayout sidePane = (FrameLayout) findViewById(R.id.detail); MyApp.LogDebug(LOG_TAG, "openLectureDetail sidePane="+sidePane); if (sidePane != null) { FragmentManager fm = getSupportFragmentManager(); sidePane.setVisibility(View.VISIBLE); FragmentTransaction fragmentTransaction = fm.beginTransaction(); EventDetailFragment ev = new EventDetailFragment(); Bundle args = new Bundle(); args.putString("title", lecture.title); args.putString("subtitle", lecture.subtitle); args.putString("abstract", lecture.abstractt); args.putString("descr", lecture.description); args.putString("spkr", lecture.speakers.replaceAll(";", ", ")); args.putString("links", lecture.links); args.putString("eventid", lecture.lecture_id); args.putInt("time", lecture.startTime); args.putInt("day", mDay); args.putString("room", lecture.room); args.putBoolean("sidepane", true); ev.setArguments(args); fragmentTransaction.replace(R.id.detail, ev, "detail"); fragmentTransaction.commit(); } else { Intent intent = new Intent(this, EventDetail.class); intent.putExtra("title", lecture.title); intent.putExtra("subtitle", lecture.subtitle); intent.putExtra("abstract", lecture.abstractt); intent.putExtra("descr", lecture.description); intent.putExtra("spkr", lecture.speakers.replaceAll(";", ", ")); intent.putExtra("links", lecture.links); intent.putExtra("eventid", lecture.lecture_id); intent.putExtra("time", lecture.startTime); intent.putExtra("day", mDay); intent.putExtra("room", lecture.room); startActivityForResult(intent, MyApp.EVENTVIEW); } } @Override public void closeDetailView() { View sidePane = findViewById(R.id.detail); if (sidePane != null) sidePane.setVisibility(View.GONE); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentByTag("detail"); if (fragment != null) { FragmentTransaction fragmentTransaction = fm.beginTransaction(); fragmentTransaction.remove(fragment).commit(); } } @Override public void refreshEventMarkers() { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentByTag("schedule"); if (fragment != null) { ((FahrplanFragment)fragment).refreshEventMarkers(); } } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case MyApp.ALARMLIST: case MyApp.EVENTVIEW: if (resultCode == SherlockFragmentActivity.RESULT_OK) { refreshEventMarkers(); } break; } } @Override public void cert_accepted() { MyApp.LogDebug(LOG_TAG, "fetch on cert accepted."); fetchFahrplan(MainActivity.this); } @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); Fragment detail = fm.findFragmentByTag("detail"); if (detail != null) { fm.beginTransaction().remove(detail).commit(); View sidePane = findViewById(R.id.detail); if (sidePane != null) sidePane.setVisibility(View.GONE); supportInvalidateOptionsMenu(); } else { finish(); } } }
package edu.wustl.catissuecore.action; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.cde.CDE; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.cde.PermissibleValue; import edu.wustl.common.util.SearchUtil; import edu.wustl.common.util.logger.Logger; public class SpecimenSearchAction extends BaseAction { /** * Overrides the execute method of Action class. * Initializes the various fields in SpecimenSearch.jsp Page. * */ public ActionForward executeAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Setting the Sepecimen Type list List specimenTypeList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_SPECIMEN_TYPE,null); request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList); //Setting Tissue Site list NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED); List tissueSiteList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_TISSUE_SITE,undefinedVal); request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList); //Setting Tissue Side list NameValueBean unknownVal = new NameValueBean(Constants.UNKNOWN,Constants.UNKNOWN); List tissueSideList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_TISSUE_SIDE,unknownVal); request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList); //Setting Pathological Status list List pathologicalStatusList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_PATHOLOGICAL_STATUS,null); request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList); //Setting Biohazard type list List biohazardList = CDEManager.getCDEManager().getList(Constants.CDE_NAME_BIOHAZARD,null); request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList); //Setting the operators list in request scope request.setAttribute(Constants.STRING_OPERATORS,SearchUtil.getOperatorList(SearchUtil.DATATYPE_STRING)); request.setAttribute(Constants.DATE_NUMERIC_OPERATORS,SearchUtil.getOperatorList(SearchUtil.DATATYPE_NUMERIC)); request.setAttribute(Constants.ENUMERATED_OPERATORS,SearchUtil.getOperatorList(SearchUtil.DATATYPE_ENUMERATED)); try { // get the Specimen class and type from the cde CDE specimenClassCDE = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_SPECIMEN_CLASS); Set setPV = specimenClassCDE.getPermissibleValues(); Iterator itr = setPV.iterator(); List specimenClassList = new ArrayList(); Map subTypeMap = new HashMap(); specimenClassList.add(new NameValueBean(Constants.SELECT_OPTION,"-1")); //Creating a map of subtypes against their types (class names) while(itr.hasNext()) { List innerList = new ArrayList(); Object obj = itr.next(); PermissibleValue pv = (PermissibleValue)obj; String tmpStr = pv.getValue(); Logger.out.debug(tmpStr); specimenClassList.add(new NameValueBean( tmpStr,tmpStr)); Set list1 = pv.getSubPermissibleValues(); Iterator itr1 = list1.iterator(); innerList.add(new NameValueBean(Constants.SELECT_OPTION,"-1")); while(itr1.hasNext()) { Object obj1 = itr1.next(); PermissibleValue pv1 = (PermissibleValue)obj1; //Setting the specimen type String tmpInnerStr = pv1.getValue(); innerList.add(new NameValueBean( tmpInnerStr,tmpInnerStr)); } subTypeMap.put(pv.getValue(),innerList); } //Setting the class list request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList); //Setting the map of subtypes request.setAttribute(Constants.SPECIMEN_TYPE_MAP, subTypeMap); } catch(Exception excp) { Logger.out.error(excp.getMessage(),excp); return mapping.findForward(Constants.FAILURE); } String pageOf = (String)request.getParameter(Constants.PAGEOF); return mapping.findForward(pageOf); } }
package com.speearth.view.prenotaservizio; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Optional; import java.util.ResourceBundle; import com.speearth.controller.AppFacadeController; import com.speearth.model.core.Alloggio; import com.speearth.model.core.Biglietto; import com.speearth.model.core.IServizioComponent; import com.speearth.model.core.PacchettoComposite; import com.speearth.utility.Costanti; import com.speearth.view.EventoSelezionaServizio; import com.speearth.view.View; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.DatePicker; import javafx.scene.control.ListView; import javafx.scene.control.MenuButton; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.stage.Stage; import javafx.util.Callback; public class RicercaPacchettoView extends View { @FXML private Button bottone_scegli_servizio; @FXML private Button bottone_ricerca; @FXML private Button bottone_riepilogo; @FXML private Button bottone_svuota; @FXML private Button bottone_conferma; @FXML private TextField input_partenza; @FXML private TextField input_destinazione; @FXML private DatePicker input_data_andata; @FXML private DatePicker input_data_ritorno; @FXML private Button ricerca_biglietti; @FXML private MenuButton input_mezzo; @FXML private MenuButton input_bambini; @FXML private MenuButton input_adulti; @FXML private MenuButton input_ora_ritorno; @FXML private MenuButton input_ora_andata; @FXML private TextField input_localita; @FXML private DatePicker input_data_arrivo; @FXML private DatePicker input_data_partenza; @FXML private Button ricerca_alloggi; @FXML private MenuButton input_numero_singole; @FXML private MenuButton input_ora_partenza; @FXML private MenuButton input_ora_arrivo; @FXML private CheckBox input_singola; @FXML private CheckBox input_doppia; @FXML private CheckBox input_tripla; @FXML private CheckBox input_quadrupla; @FXML private MenuButton input_numero_doppie; @FXML private MenuButton input_numero_triple; @FXML private MenuButton input_numero_quadruple; @FXML private ListView<Biglietto> lista_risultati_biglietti; @FXML private ListView<Alloggio> lista_risultati_alloggi; @FXML private TableView<IServizioComponent> tabella_pacchetto; @FXML private TableColumn<IServizioComponent, String> tipo_servizio_col; @FXML private TableColumn<IServizioComponent, String> fornitore_servizio_col; @FXML private TableColumn<IServizioComponent, String> prezzo_servizio_col; private ObservableList<Biglietto> lista_biglietti = FXCollections.observableArrayList(); private ObservableList<Alloggio> lista_alloggi = FXCollections.observableArrayList(); private ObservableList<IServizioComponent> list_servizi = FXCollections.observableArrayList(); /** * Pacchetto contenuto nella SubView */ private PacchettoComposite pacchetto; public RicercaPacchettoView(Stage stage) throws IOException { super(stage); getStage().setTitle(Costanti.TITOLO_PRENOTA_PACCHETTO); this.pacchetto = new PacchettoComposite(); getParentNode().addEventHandler(EventoSelezionaServizio.SERVIZIO_SELEZIONATO, new EventHandler<EventoSelezionaServizio>() { @Override public void handle(EventoSelezionaServizio event) { list_servizi.add(event.getServizio()); pacchetto.aggiungi(event.getServizio()); } }); initializeServiceTable(); } /** * Inizializza la classe * * @param arg0 * @param arg1 */ @Override public void initialize(URL arg0, ResourceBundle arg1) { this.lista_risultati_biglietti.setCellFactory(param -> new BigliettoItemList(getStage())); this.lista_risultati_biglietti.setItems(this.lista_biglietti); this.lista_risultati_alloggi.setCellFactory(param -> new AlloggioItemList(getStage())); this.lista_risultati_alloggi.setItems(this.lista_alloggi); this.bottone_ricerca.setDisable(true); } /** * Inizializza la tabella dei servizi scelti */ public void initializeServiceTable() { this.tipo_servizio_col.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<IServizioComponent, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(CellDataFeatures<IServizioComponent, String> param) { IServizioComponent servizio = param.getValue(); SimpleStringProperty tipo = null; if (servizio instanceof Alloggio) tipo = new SimpleStringProperty("Alloggio"); else if (servizio instanceof Biglietto) tipo = new SimpleStringProperty("Biglietto"); return tipo; } }); this.fornitore_servizio_col.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<IServizioComponent, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(CellDataFeatures<IServizioComponent, String> param) { IServizioComponent servizio = param.getValue(); SimpleStringProperty fornitore = null; if (servizio instanceof Alloggio) fornitore = new SimpleStringProperty(((Alloggio) servizio).getFornitore()); else if (servizio instanceof Biglietto) fornitore = new SimpleStringProperty(((Biglietto) servizio).getFornitore()); return fornitore; } }); this.prezzo_servizio_col.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<IServizioComponent, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(CellDataFeatures<IServizioComponent, String> param) { IServizioComponent servizio = param.getValue(); SimpleStringProperty prezzo = null; if (servizio instanceof Alloggio) prezzo = new SimpleStringProperty(Float.toString(((Alloggio) servizio).getPrezzo())); else if (servizio instanceof Biglietto) prezzo = new SimpleStringProperty(Float.toString(((Biglietto) servizio).getPrezzo())); return prezzo; } }); this.list_servizi.setAll(this.pacchetto.getListaServizi()); this.tabella_pacchetto.setItems(this.list_servizi); } // Event Listener on Button[#bottone_scegli_servizio].onAction @FXML public void vaiAScegliServizio(ActionEvent event) throws IOException { if (this.lista_biglietti.isEmpty() && this.lista_alloggi.isEmpty()) mostraPrecedente(); else { Optional<ButtonType> result = mostraAlert(AlertType.CONFIRMATION, Costanti.TITOLO_TORNA_A_SCEGLI_SERVIZIO, null, Costanti.MESSAGGIO_TORNA_A_SCELTA_SERVIZIO); if (result.get() == ButtonType.OK) { AppFacadeController.getInstance().getPrenotaServizioController().getPrenotaPacchettoController() .setPacchetto(null); mostraPrecedente(); } } } // Event Listener on Button[#bottone_ricerca].onAction @FXML public void vaiARicerca(ActionEvent event) throws IOException { // TODO ricerca } // Event Listener on Button[#bottone_ricerca].onAction @FXML public void vaiARiepilogo(ActionEvent event) throws IOException { if (AppFacadeController.getInstance().getPrenotaServizioController().getPrenotaPacchettoController() .getPacchetto() == null) mostraAlert(AlertType.ERROR, Costanti.TITOLO_NESSUN_SERVIZIO, null, Costanti.MESSAGGIO_NESSUN_SERVIZIO); else { RiepilogoPacchettoView view = new RiepilogoPacchettoView(getStage()); view.setPreviousView(this); view.mostra(); } } // Event Listener on Button[#bottone_svuota].onAction @FXML public void svuotaPacchetto(ActionEvent event) { Optional<ButtonType> result = mostraAlert(AlertType.CONFIRMATION, Costanti.TITOLO_SVUOTA_PACCHETTO, null, Costanti.MESSAGGIO_SVUOTA_PACCHETTO); if (result.get() == ButtonType.OK) { // cancellare la TableView this.pacchetto.getListaServizi().clear(); AppFacadeController.getInstance().getPrenotaServizioController().getPrenotaPacchettoController() .setPacchetto(null); this.list_servizi.clear(); } } // Event Listener on Button[#bottone_conferma].onAction @FXML public void confermaPacchetto(ActionEvent event) throws IOException { if (!this.pacchetto.getListaServizi().isEmpty()) AppFacadeController.getInstance().getPrenotaServizioController().getPrenotaPacchettoController() .setPacchetto(this.pacchetto); vaiARiepilogo(event); } /** * Recupera i dati inseriti dall'Utente nella form di ricerca della tab * Biglietti * * @return HashMap<String, String> */ private HashMap<String, String> recuperaDatiBiglietti() { HashMap<String, String> parametri = new HashMap<String, String>(); parametri.put("numero_adulti", this.input_adulti.getText()); parametri.put("numero_bambini", this.input_bambini.getText()); parametri.put("partenza", this.input_partenza.getText()); parametri.put("destinazione", this.input_destinazione.getText()); parametri.put("data_andata", this.input_data_andata.toString()); parametri.put("data_ritorno", this.input_data_ritorno.toString()); parametri.put("ora_andata", this.input_ora_andata.getText()); parametri.put("ora_ritorno", this.input_ora_ritorno.getText()); parametri.put("mezzo", this.input_mezzo.getText()); return parametri; } // Event Listener on Button[#ricerca_biglietti].onAction @FXML public void ricercaBiglietti(ActionEvent event) { try { HashMap<String, String> dati = this.recuperaDatiBiglietti(); ArrayList<Biglietto> risultati = AppFacadeController.getInstance().getPrenotaServizioController() .getPrenotaPacchettoController().prenotaBigliettoController().ricerca(dati); this.lista_biglietti.clear(); this.lista_biglietti.setAll(risultati); this.lista_risultati_biglietti.setItems(this.lista_biglietti); } catch (NullPointerException e) { e.printStackTrace(); mostraAlert(AlertType.ERROR, Costanti.TITOLO_ERRORE, null, Costanti.MESSAGGIO_PARAMETRI_MANCANTI); } } /** * Recupera i dati inseriti dall'Utente nella form di ricerca della tab * Alloggi * * @return HashMap<String, String> */ private HashMap<String, String> recuperaDatiAlloggi() { HashMap<String, String> parametri = new HashMap<String, String>(); parametri.put("data_arrivo", this.input_data_arrivo.toString()); parametri.put("data_partenza", this.input_data_partenza.toString()); parametri.put("stanza_doppia", this.input_doppia.getText()); parametri.put("localit", this.input_localita.getText()); parametri.put("numero_doppie", this.input_numero_doppie.getText()); parametri.put("numero_quadruple", this.input_numero_quadruple.getText()); parametri.put("numero_singole", this.input_numero_singole.getText()); parametri.put("numero_triple", this.input_numero_triple.getText()); parametri.put("ora_arrivo", this.input_ora_arrivo.getText()); parametri.put("ora_partenza", this.input_ora_partenza.getText()); parametri.put("stanza_quadrupla", this.input_quadrupla.getText()); parametri.put("stanza_singola", this.input_singola.getText()); parametri.put("stanza_tripla", this.input_tripla.getText()); return parametri; } // Event Listener on Button[#ricerca_alloggi].onAction @FXML public void ricercaAlloggi(ActionEvent event) { try { HashMap<String, String> dati = this.recuperaDatiAlloggi(); ArrayList<Alloggio> risultati = AppFacadeController.getInstance().getPrenotaServizioController() .getPrenotaPacchettoController().prenotaAlloggioController().ricerca(dati); this.lista_alloggi.clear(); this.lista_alloggi.setAll(risultati); this.lista_risultati_alloggi.setItems(lista_alloggi); } catch (NullPointerException e) { e.printStackTrace(); mostraAlert(AlertType.ERROR, Costanti.TITOLO_ERRORE, null, Costanti.MESSAGGIO_PARAMETRI_MANCANTI); } } /** * Restituisce il nome della Risorsa associata alla View * * @return String */ @Override public String getResourceName() { return Costanti.FXML_RICERCA_PACCHETTO; } }
package b_stream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.regex.Pattern; import java.util.stream.Stream; class LongestWordInFile { public static void main(String[] args) throws IOException { Pattern wordSeparator = Pattern.compile("[\\P{L}]+"); try(Stream<String> lines = Files.lines(Paths.get("frankenstein.txt"))) { System.out.println(lines.flatMap(l -> wordSeparator.splitAsStream(l)) .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get()); } } }
package edu.wustl.catissuecore.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.json.JSONArray; import org.json.JSONObject; import edu.wustl.catissuecore.actionForm.NewSpecimenForm; import edu.wustl.catissuecore.bean.CollectionProtocolBean; import edu.wustl.catissuecore.bean.CollectionProtocolEventBean; import edu.wustl.catissuecore.bean.GenericSpecimen; import edu.wustl.catissuecore.bean.SpecimenRequirementBean; import edu.wustl.catissuecore.bizlogic.CollectionProtocolBizLogic; import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic; import edu.wustl.catissuecore.domain.AbstractSpecimen; import edu.wustl.catissuecore.domain.CellSpecimenRequirement; import edu.wustl.catissuecore.domain.ClinicalDiagnosis; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.CollectionProtocolEvent; import edu.wustl.catissuecore.domain.ConsentTier; import edu.wustl.catissuecore.domain.FluidSpecimenRequirement; import edu.wustl.catissuecore.domain.MolecularSpecimenRequirement; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Site; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCharacteristics; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.SpecimenEventParameters; import edu.wustl.catissuecore.domain.SpecimenRequirement; import edu.wustl.catissuecore.domain.TissueSpecimenRequirement; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.multiRepository.bean.SiteUserRolePrivilegeBean; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.exception.ApplicationException; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.exception.ErrorKey; import edu.wustl.common.factory.AbstractFactoryConfig; import edu.wustl.common.factory.IFactory; import edu.wustl.common.util.Utility; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.common.util.global.Status; import edu.wustl.common.util.logger.Logger; import edu.wustl.dao.DAO; import edu.wustl.dao.exception.DAOException; import edu.wustl.labelSQLApp.bizlogic.LabelSQLAssociationBizlogic; import edu.wustl.labelSQLApp.domain.LabelSQL; import edu.wustl.labelSQLApp.domain.LabelSQLAssociation; // TODO: Auto-generated Javadoc /** * The Class CollectionProtocolUtil. */ public class CollectionProtocolUtil { /** The Constant LOGGER. */ private static final Logger LOGGER = Logger.getCommonLogger(CollectionProtocolUtil.class); /** The Constant MOLECULAR_SPECIMEN_CLASS. */ private static final String MOLECULAR_SPECIMEN_CLASS = "Molecular"; /** The event bean. */ private final LinkedHashMap<String, CollectionProtocolEventBean> eventBean = new LinkedHashMap<String, CollectionProtocolEventBean>(); /** The Constant STORAGE_TYPE_ARR. */ private static final String STORAGE_TYPE_ARR[] = {"Virtual", "Auto", "Manual"}; /** * Gets the storage type value. * * @param type the type * * @return the storage type value */ public static Integer getStorageTypeValue(String type) { int returnVal = Integer.valueOf(0); for (int ctr = 0; ctr < STORAGE_TYPE_ARR.length; ctr++) { if (STORAGE_TYPE_ARR[ctr].equals(type)) { returnVal = Integer.valueOf(ctr); break; } } return returnVal; //default considered as 'Virtual'; } /** * Gets the storage type value. * * @param type the type * * @return the storage type value */ public static String getStorageTypeValue(Integer type) { String storeArr;//STORAGE_TYPE_ARR[type.intValue()]; if (type == null) { storeArr = STORAGE_TYPE_ARR[0]; //default considered as 'Virtual'; } else { storeArr = STORAGE_TYPE_ARR[type.intValue()]; } //if(type.intValue()>2) return storageTypeArr[1]; return storeArr; } /** * Gets the collection protocol bean. * * @param collectionProtocol the collection protocol * * @return the collection protocol bean */ public static CollectionProtocolBean getCollectionProtocolBean( CollectionProtocol collectionProtocol) { CollectionProtocolBean collectionProtocolBean; collectionProtocolBean = new CollectionProtocolBean(); collectionProtocolBean.setConsentTierCounter(collectionProtocol.getConsentTierCollection() .size()); Long identifier = Long.valueOf(collectionProtocol.getId().longValue()); collectionProtocolBean.setIdentifier(identifier); long[] coordinatorIds = null; coordinatorIds = getProtocolCordnateIds(collectionProtocol, coordinatorIds); collectionProtocolBean.setCoordinatorIds(coordinatorIds); collectionProtocolBean.setCoordinatorCollection(collectionProtocol .getCoordinatorCollection()); /**For Clinical Diagnosis subset **/ collectionProtocolBean.setClinicalDiagnosis(getClinicalDiagnosis(collectionProtocol)); setBasicCPProps(collectionProtocol, collectionProtocolBean); if (collectionProtocol.getCollectionProtocolRegistrationCollection().size() > 0) { collectionProtocolBean.setParticiapantReg(true); } collectionProtocolBean.setType(collectionProtocol.getType()); collectionProtocolBean.setSequenceNumber(collectionProtocol.getSequenceNumber()); collectionProtocolBean.setStudyCalendarEventPoint(collectionProtocol .getStudyCalendarEventPoint()); if (collectionProtocol.getParentCollectionProtocol() != null) { collectionProtocolBean.setParentCollectionProtocolId(collectionProtocol .getParentCollectionProtocol().getId()); } return collectionProtocolBean; } /** * Sets the basic cp props. * * @param collectionProtocol the collection protocol * @param collectionProtocolBean the collection protocol bean */ private static void setBasicCPProps(CollectionProtocol collectionProtocol, CollectionProtocolBean collectionProtocolBean) { collectionProtocolBean.setPrincipalInvestigatorId(collectionProtocol .getPrincipalInvestigator().getId().longValue()); Date date = collectionProtocol.getStartDate(); collectionProtocolBean.setStartDate(edu.wustl.common.util.Utility.parseDateToString(date, Constants.DATE_FORMAT)); collectionProtocolBean.setDescriptionURL(collectionProtocol.getDescriptionURL()); collectionProtocolBean.setUnsignedConsentURLName(collectionProtocol .getUnsignedConsentDocumentURL()); setLabelFormatProps(collectionProtocol, collectionProtocolBean); if (collectionProtocol.getConsentsWaived() == null) { collectionProtocol.setConsentsWaived(false); } if (collectionProtocol.getIsEMPIEnabled() == null) { collectionProtocol.setIsEMPIEnabled(false); } collectionProtocolBean.setConsentWaived(collectionProtocol.getConsentsWaived() .booleanValue()); collectionProtocolBean .setIsEMPIEnable(collectionProtocol.getIsEMPIEnabled().booleanValue()); collectionProtocolBean.setIrbID(collectionProtocol.getIrbIdentifier()); collectionProtocolBean.setTitle(collectionProtocol.getTitle()); collectionProtocolBean.setShortTitle(collectionProtocol.getShortTitle()); collectionProtocolBean.setEnrollment(String.valueOf(collectionProtocol.getEnrollment())); collectionProtocolBean.setConsentValues(prepareConsentTierMap(collectionProtocol .getConsentTierCollection())); collectionProtocolBean.setActivityStatus(collectionProtocol.getActivityStatus()); collectionProtocolBean.setAliqoutInSameContainer(collectionProtocol .getAliquotInSameContainer().booleanValue()); String endDate = Utility.parseDateToString(collectionProtocol.getEndDate(), CommonServiceLocator.getInstance().getDatePattern()); collectionProtocolBean.setEndDate(endDate); } /** * Sets label format properties. * * @param collectionProtocol the collection protocol * @param collectionProtocolBean the collection protocol bean */ private static void setLabelFormatProps(CollectionProtocol collectionProtocol, CollectionProtocolBean collectionProtocolBean) { collectionProtocolBean.setLabelFormat(collectionProtocol.getSpecimenLabelFormat()); collectionProtocolBean.setDerivativeLabelFormat(collectionProtocol .getDerivativeLabelFormat()); collectionProtocolBean.setAliquotLabelFormat(collectionProtocol.getAliquotLabelFormat()); } /** * Gets the protocol cordnate ids. * * @param collectionProtocol the collection protocol * @param coordinatorIds the coordinator ids * * @return the protocol cordnate ids */ private static long[] getProtocolCordnateIds(CollectionProtocol collectionProtocol, long[] coordinatorIds) { Collection userCollection = collectionProtocol.getCoordinatorCollection(); if (userCollection != null) { coordinatorIds = new long[userCollection.size()]; int counter = 0; Iterator iterator = userCollection.iterator(); while (iterator.hasNext()) { User user = (User) iterator.next(); coordinatorIds[counter] = user.getId().longValue(); counter++; } } return coordinatorIds; } /** * Returns string array of clinical diagnosis. * * @param collectionProtocol the collection protocol * * @return the clinical diagnosis */ private static String[] getClinicalDiagnosis(CollectionProtocol collectionProtocol) { String[] clinicalDiagnosisArr = null; Collection<ClinicalDiagnosis> clinicDiagnosisCollection = collectionProtocol .getClinicalDiagnosisCollection(); if (clinicDiagnosisCollection != null) { clinicalDiagnosisArr = new String[clinicDiagnosisCollection.size()]; int index = 0; Iterator<ClinicalDiagnosis> iterator = clinicDiagnosisCollection.iterator(); while (iterator.hasNext()) { ClinicalDiagnosis clinicalDiagnosis = iterator.next(); clinicalDiagnosisArr[index] = clinicalDiagnosis.getName(); index++; } } return clinicalDiagnosisArr; } /** * Prepare consent tier map. * * @param consentTierColl the consent tier coll * * @return the map */ public static Map prepareConsentTierMap(Collection consentTierColl) { Map tempMap = new LinkedHashMap();//bug 8905 List<ConsentTier> consentsList = new ArrayList<ConsentTier>(); if (consentTierColl != null) { consentsList.addAll(consentTierColl);//bug 8905 Collections.sort(consentsList, new IdComparator());//bug 8905 //Iterator consentTierCollIter = consentTierColl.iterator(); Iterator consentTierCollIter = consentsList.iterator();//bug 8905 int counter = 0; while (consentTierCollIter.hasNext()) { ConsentTier consent = (ConsentTier) consentTierCollIter.next(); String statement = "ConsentBean:" + counter + "_statement"; String statementkey = "ConsentBean:" + counter + "_consentTierID"; tempMap.put(statement, consent.getStatement()); tempMap.put(statementkey, String.valueOf(consent.getId())); counter++; } } return tempMap; } /** * Gets the collection protocol event bean. * * @param collectionProtocolEvent the collection protocol event * @param counter the counter * @param dao the dao * * @return the collection protocol event bean * * @throws DAOException the DAO exception */ public static CollectionProtocolEventBean getCollectionProtocolEventBean( CollectionProtocolEvent collectionProtocolEvent, int counter, DAO dao) throws DAOException { CollectionProtocolEventBean eventBean = new CollectionProtocolEventBean(); eventBean.setId(collectionProtocolEvent.getId().longValue()); eventBean.setStudyCalenderEventPoint(new Double(collectionProtocolEvent .getStudyCalendarEventPoint())); eventBean.setCollectionPointLabel(collectionProtocolEvent.getCollectionPointLabel()); eventBean.setClinicalDiagnosis(collectionProtocolEvent.getClinicalDiagnosis()); eventBean.setClinicalStatus(collectionProtocolEvent.getClinicalStatus()); eventBean.setId(collectionProtocolEvent.getId().longValue()); eventBean.setUniqueIdentifier("E" + counter++); eventBean.setSpecimenCollRequirementGroupId(collectionProtocolEvent.getId().longValue()); eventBean.setSpecimenRequirementbeanMap(getSpecimensMap(collectionProtocolEvent .getSpecimenRequirementCollection(), eventBean.getUniqueIdentifier())); eventBean.setLabelFormat(collectionProtocolEvent.getLabelFormat()); if (collectionProtocolEvent.getDefaultSite() != null) eventBean.setDefaultSiteId(collectionProtocolEvent.getDefaultSite().getId()); return eventBean; } /** * Gets the sorted cp event list. * * @param genericList the generic list * * @return the sorted cp event list */ public static List getSortedCPEventList(List genericList) { //Comparator to sort the List of Map chronologically. final Comparator identifierComparator = new Comparator() { public int compare(Object object1, Object object2) { Long identifier1 = null; Long identifier2 = null; if (object1 instanceof CollectionProtocolEvent) { identifier1 = ((CollectionProtocolEvent) object1).getId(); identifier2 = ((CollectionProtocolEvent) object2).getId(); } else if (object1 instanceof SpecimenRequirement) { identifier1 = ((SpecimenRequirement) object1).getId(); identifier2 = ((SpecimenRequirement) object2).getId(); } else if (object1 instanceof AbstractSpecimen) { identifier1 = ((AbstractSpecimen) object1).getId(); identifier2 = ((AbstractSpecimen) object2).getId(); } if (identifier1 != null && identifier2 != null) { return identifier1.compareTo(identifier2); } if (identifier1 == null) { return -1; } if (identifier2 == null) { return 1; } return 0; } }; Collections.sort(genericList, identifierComparator); return genericList; } /** * Gets the specimens map. * * @param reqSpecimenCollection the req specimen collection * @param parentUniqueId the parent unique id * * @return the specimens map */ public static LinkedHashMap<String, GenericSpecimen> getSpecimensMap( Collection<SpecimenRequirement> reqSpecimenCollection, String parentUniqueId) { LinkedHashMap<String, GenericSpecimen> reqSpecimenMap = new LinkedHashMap<String, GenericSpecimen>(); List<SpecimenRequirement> reqSpecimenList = new LinkedList<SpecimenRequirement>( reqSpecimenCollection); getSortedCPEventList(reqSpecimenList); Iterator<SpecimenRequirement> specimenIterator = reqSpecimenList.iterator(); int specCtr = 0; while (specimenIterator.hasNext()) { SpecimenRequirement reqSpecimen = specimenIterator.next(); if (reqSpecimen.getParentSpecimen() == null) { SpecimenRequirementBean specBean = getSpecimenBean(reqSpecimen, null, parentUniqueId, specCtr++); reqSpecimenMap.put(specBean.getUniqueIdentifier(), specBean); } } return reqSpecimenMap; } /** * Gets the child aliquots. * * @param reqSpecimen the req specimen * @param parentuniqueId the parentunique id * @param parentName the parent name * * @return the child aliquots */ private static LinkedHashMap<String, GenericSpecimen> getChildAliquots( SpecimenRequirement reqSpecimen, String parentuniqueId, String parentName) { Collection reqSpecimenChildren = reqSpecimen.getChildSpecimenCollection(); List reqSpecimenList = new LinkedList<SpecimenRequirement>(reqSpecimenChildren); getSortedCPEventList(reqSpecimenList); Iterator<SpecimenRequirement> iterator = reqSpecimenList.iterator(); LinkedHashMap<String, GenericSpecimen> aliquotMap = new LinkedHashMap<String, GenericSpecimen>(); int aliqCtr = 1; while (iterator.hasNext()) { SpecimenRequirement childReqSpecimen = iterator.next(); if (Constants.ALIQUOT.equals(childReqSpecimen.getLineage())) { SpecimenRequirementBean specimenBean = getSpecimenBean(childReqSpecimen, parentName, parentuniqueId, aliqCtr++); aliquotMap.put(specimenBean.getUniqueIdentifier(), specimenBean); } } return aliquotMap; } /** * Gets the child derived. * * @param specimen the specimen * @param parentuniqueId the parentunique id * @param parentName the parent name * * @return the child derived */ private static LinkedHashMap<String, GenericSpecimen> getChildDerived( SpecimenRequirement specimen, String parentuniqueId, String parentName) { Collection specimenChildren = specimen.getChildSpecimenCollection(); List specimenList = new LinkedList(specimenChildren); getSortedCPEventList(specimenList); Iterator<SpecimenRequirement> iterator = specimenList.iterator(); LinkedHashMap<String, GenericSpecimen> derivedMap = new LinkedHashMap<String, GenericSpecimen>(); int deriveCtr = 1; while (iterator.hasNext()) { SpecimenRequirement childReqSpecimen = iterator.next(); if (Constants.DERIVED_SPECIMEN.equals(childReqSpecimen.getLineage())) { SpecimenRequirementBean specimenBean = getSpecimenBean(childReqSpecimen, parentName, parentuniqueId, deriveCtr++); derivedMap.put(specimenBean.getUniqueIdentifier(), specimenBean); } } return derivedMap; } /** * Gets the unique id. * * @param lineage the lineage * @param ctr the ctr * * @return the unique id */ private static String getUniqueId(String lineage, int ctr) { String constantVal = null; if (Constants.NEW_SPECIMEN.equals(lineage)) { constantVal = Constants.UNIQUE_IDENTIFIER_FOR_NEW_SPECIMEN + ctr; } else if (Constants.DERIVED_SPECIMEN.equals(lineage)) { constantVal = Constants.UNIQUE_IDENTIFIER_FOR_DERIVE + ctr; } else if (Constants.ALIQUOT.equals(lineage)) { constantVal = Constants.UNIQUE_IDENTIFIER_FOR_ALIQUOT + ctr; } return constantVal; } /** * Gets the specimen bean. * * @param reqSpecimen the req specimen * @param parentName the parent name * @param parentUniqueId the parent unique id * @param specCtr the spec ctr * * @return the specimen bean */ private static SpecimenRequirementBean getSpecimenBean(SpecimenRequirement reqSpecimen, String parentName, String parentUniqueId, int specCtr) { SpecimenRequirementBean speRequirementBean = new SpecimenRequirementBean(); speRequirementBean.setId(reqSpecimen.getId().longValue()); speRequirementBean.setLineage(reqSpecimen.getLineage()); speRequirementBean.setUniqueIdentifier(parentUniqueId + getUniqueId(reqSpecimen.getLineage(), specCtr)); speRequirementBean.setDisplayName(Constants.ALIAS_SPECIMEN + "_" + speRequirementBean.getUniqueIdentifier()); speRequirementBean.setClassName(reqSpecimen.getClassName()); speRequirementBean.setType(reqSpecimen.getSpecimenType()); speRequirementBean.setId(reqSpecimen.getId().longValue()); SpecimenCharacteristics characteristics = reqSpecimen.getSpecimenCharacteristics(); updateSpeRequirementBean(reqSpecimen, speRequirementBean, characteristics); Double quantity = reqSpecimen.getInitialQuantity(); if (quantity != null) { speRequirementBean.setQuantity(String.valueOf(quantity)); } if (reqSpecimen.getStorageType() != null) { speRequirementBean.setStorageContainerForSpecimen(reqSpecimen.getStorageType()); } setSpecimenEventParameters(reqSpecimen, speRequirementBean); setAliquotAndDerivedColl(reqSpecimen, parentName, speRequirementBean); speRequirementBean.setLabelFormat(reqSpecimen.getLabelFormat()); return speRequirementBean; } /** * set Specimen Requirements. * * @param reqSpecimen the req specimen * @param speRequirementBean the spe requirement bean * @param characteristics the characteristics */ private static void updateSpeRequirementBean(SpecimenRequirement reqSpecimen, SpecimenRequirementBean speRequirementBean, SpecimenCharacteristics characteristics) { if (characteristics != null) { speRequirementBean.setTissueSite(characteristics.getTissueSite()); speRequirementBean.setTissueSide(characteristics.getTissueSide()); } speRequirementBean.setSpecimenCharsId(reqSpecimen.getSpecimenCharacteristics().getId() .longValue()); speRequirementBean.setPathologicalStatus(reqSpecimen.getPathologicalStatus()); if (MOLECULAR_SPECIMEN_CLASS.equals(reqSpecimen.getClassName())) { Double concentration = ((MolecularSpecimenRequirement) reqSpecimen) .getConcentrationInMicrogramPerMicroliter(); if (concentration != null) { speRequirementBean.setConcentration(String.valueOf(concentration.doubleValue())); } } } /** * Sets the aliquot and derived coll. * * @param reqSpecimen the req specimen * @param parentName the parent name * @param speRequirementBean the spe requirement bean */ private static void setAliquotAndDerivedColl(SpecimenRequirement reqSpecimen, String parentName, SpecimenRequirementBean speRequirementBean) { speRequirementBean.setParentName(parentName); LinkedHashMap<String, GenericSpecimen> aliquotMap = getChildAliquots(reqSpecimen, speRequirementBean.getUniqueIdentifier(), speRequirementBean.getDisplayName()); LinkedHashMap<String, GenericSpecimen> derivedMap = getChildDerived(reqSpecimen, speRequirementBean.getUniqueIdentifier(), speRequirementBean.getDisplayName()); Collection aliquotCollection = aliquotMap.values(); Collection derivedCollection = derivedMap.values(); //added method setQuantityPerAliquot(speRequirementBean, aliquotCollection); speRequirementBean.setNoOfAliquots(String.valueOf(aliquotCollection.size())); speRequirementBean.setAliquotSpecimenCollection(aliquotMap); speRequirementBean.setDeriveSpecimenCollection(derivedMap); speRequirementBean.setNoOfDeriveSpecimen(derivedCollection.size()); derivedMap = getDerviredObjectMap(derivedMap.values()); speRequirementBean.setDeriveSpecimen(derivedMap); setDeriveQuantity(speRequirementBean, derivedCollection); } /** * set specimen requirement bean by DerivedCollection. * * @param speRequirementBean the spe requirement bean * @param derivedCollection the derived collection */ private static void setDeriveQuantity(SpecimenRequirementBean speRequirementBean, Collection derivedCollection) { if (derivedCollection != null && !derivedCollection.isEmpty()) { Iterator iterator = derivedCollection.iterator(); GenericSpecimen derivedSpecimen = (GenericSpecimen) iterator.next(); speRequirementBean.setDeriveClassName(derivedSpecimen.getClassName()); speRequirementBean.setDeriveType(derivedSpecimen.getType()); speRequirementBean.setDeriveConcentration(derivedSpecimen.getConcentration()); speRequirementBean.setDeriveQuantity(derivedSpecimen.getQuantity()); } } /** * set specimen requirement bean by AliquotCollection. * * @param speRequirementBean the spe requirement bean * @param aliquotCollection the aliquot collection */ private static void setQuantityPerAliquot(SpecimenRequirementBean speRequirementBean, Collection aliquotCollection) { if (aliquotCollection != null && !aliquotCollection.isEmpty()) { Iterator iterator = aliquotCollection.iterator(); GenericSpecimen aliquotSpecimen = (GenericSpecimen) iterator.next(); speRequirementBean.setStorageContainerForAliquotSpecimem(aliquotSpecimen .getStorageContainerForSpecimen()); speRequirementBean.setQuantityPerAliquot(aliquotSpecimen.getQuantity()); } } /** * Gets the dervired object map. * * @param derivedCollection the derived collection * * @return the dervired object map */ public static LinkedHashMap getDerviredObjectMap(Collection<GenericSpecimen> derivedCollection) { LinkedHashMap<String, String> derivedObjectMap = new LinkedHashMap<String, String>(); Iterator<GenericSpecimen> iterator = derivedCollection.iterator(); int deriveCtr = 1; while (iterator.hasNext()) { SpecimenRequirementBean derivedSpecimen = (SpecimenRequirementBean) iterator.next(); StringBuffer derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_id"); derivedObjectMap.put(derivedSpecimenKey.toString(), String.valueOf(derivedSpecimen .getId())); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_specimenClass"); derivedObjectMap.put(derivedSpecimenKey.toString(), derivedSpecimen.getClassName()); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_specimenType"); derivedObjectMap.put(derivedSpecimenKey.toString(), derivedSpecimen.getType()); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_storageLocation"); derivedObjectMap.put(derivedSpecimenKey.toString(), derivedSpecimen .getStorageContainerForSpecimen()); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_quantity"); String quantity = derivedSpecimen.getQuantity(); derivedObjectMap.put(derivedSpecimenKey.toString(), quantity); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_concentration"); derivedObjectMap.put(derivedSpecimenKey.toString(), derivedSpecimen.getConcentration()); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_unit"); derivedObjectMap.put(derivedSpecimenKey.toString(), ""); derivedSpecimenKey = getKeyBase(deriveCtr); derivedSpecimenKey.append("_labelFormat"); derivedObjectMap.put(derivedSpecimenKey.toString(), derivedSpecimen.getLabelFormat()); deriveCtr++; } return derivedObjectMap; } /** * Gets the key base. * * @param deriveCtr the derive ctr * * @return the key base */ private static StringBuffer getKeyBase(int deriveCtr) { StringBuffer derivedSpecimenKey = new StringBuffer(); derivedSpecimenKey.append("DeriveSpecimenBean:"); derivedSpecimenKey.append(String.valueOf(deriveCtr)); return derivedSpecimenKey; } /** * Sets the specimen event parameters. * * @param reqSpecimen the req specimen * @param specimenRequirementBean the specimen requirement bean */ private static void setSpecimenEventParameters(SpecimenRequirement reqSpecimen, SpecimenRequirementBean specimenRequirementBean) { Collection eventsParametersColl = reqSpecimen.getSpecimenEventCollection(); if (eventsParametersColl == null || eventsParametersColl.isEmpty()) { return; } Iterator iter = eventsParametersColl.iterator(); while (iter.hasNext()) { setSpecimenEvents(specimenRequirementBean, iter); } } /** * set setSpeciEevntParams. * * @param specimenRequirementBean the specimen requirement bean * @param iter the iter */ private static void setSpecimenEvents(SpecimenRequirementBean specimenRequirementBean, Iterator iter) { Object tempObj = iter.next(); if (tempObj instanceof CollectionEventParameters) { CollectionEventParameters collectionEventParameters = (CollectionEventParameters) tempObj; specimenRequirementBean.setCollectionEventId(collectionEventParameters.getId() .longValue()); //this.collectionEventSpecimenId = collectionEventParameters.getSpecimen().getId().longValue(); specimenRequirementBean.setCollectionEventUserId(collectionEventParameters.getUser() .getId().longValue()); specimenRequirementBean.setCollectionEventCollectionProcedure(collectionEventParameters .getCollectionProcedure()); specimenRequirementBean.setCollectionEventContainer(collectionEventParameters .getContainer()); } else if (tempObj instanceof ReceivedEventParameters) { ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) tempObj; specimenRequirementBean.setReceivedEventId(receivedEventParameters.getId().longValue()); specimenRequirementBean.setReceivedEventUserId(receivedEventParameters.getUser() .getId().longValue()); specimenRequirementBean.setReceivedEventReceivedQuality(receivedEventParameters .getReceivedQuality()); } } /** * Update session. * * @param request the request * @param identifieer the identifieer * * @throws ApplicationException the application exception */ public static void updateSession(HttpServletRequest request, Long identifieer) throws ApplicationException { List sessionCpList = new CollectionProtocolBizLogic().retrieveCP(identifieer); if (sessionCpList == null || sessionCpList.size() < 2) { throw new ApplicationException(ErrorKey.getErrorKey("errors.item"), null, "Fail to retrieve Collection protocol.."); } HttpSession session = request.getSession(); session.removeAttribute(Constants.COLLECTION_PROTOCOL_SESSION_BEAN); session.removeAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP); setPrivilegesForCP(identifieer, session); CollectionProtocolBean collectionProtocolBean = (CollectionProtocolBean) sessionCpList .get(0); collectionProtocolBean.setOperation("update"); session.setAttribute(Constants.COLLECTION_PROTOCOL_SESSION_BEAN, sessionCpList.get(0)); session.setAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP, sessionCpList.get(1)); String cptitle = collectionProtocolBean.getTitle(); String treeNode = "cpName_" + cptitle; session.setAttribute(Constants.TREE_NODE_ID, treeNode); session.setAttribute("tempKey", treeNode); } /** * Sets the privileges for cp. * * @param cpId the cp id * @param session the session */ private static void setPrivilegesForCP(Long cpId, HttpSession session) { Map<String, SiteUserRolePrivilegeBean> map = CaTissuePrivilegeUtility .getPrivilegesOnCP(cpId); session.setAttribute(Constants.ROW_ID_OBJECT_BEAN_MAP, map); } /** * Gets the collection protocol event map. * * @param collectionProtocolEventColl the collection protocol event coll * @param dao the dao * * @return the collection protocol event map * * @throws DAOException the DAO exception */ public static LinkedHashMap<String, CollectionProtocolEventBean> getCollectionProtocolEventMap( Collection collectionProtocolEventColl, DAO dao) throws DAOException { Iterator iterator = collectionProtocolEventColl.iterator(); LinkedHashMap<String, CollectionProtocolEventBean> eventMap = new LinkedHashMap<String, CollectionProtocolEventBean>(); int ctr = 1; while (iterator.hasNext()) { CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent) iterator .next(); CollectionProtocolEventBean eventBean = CollectionProtocolUtil .getCollectionProtocolEventBean(collectionProtocolEvent, ctr++, dao); eventMap.put(eventBean.getUniqueIdentifier(), eventBean); } return eventMap; } /** * Populate collection protocol objects. * * @param request the request * * @return the collection protocol * * @throws Exception the exception */ public static CollectionProtocol populateCollectionProtocolObjects(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); CollectionProtocolBean collectionProtocolBean = (CollectionProtocolBean) session .getAttribute(Constants.COLLECTION_PROTOCOL_SESSION_BEAN); LinkedHashMap<String, CollectionProtocolEventBean> cpEventMap = (LinkedHashMap) session .getAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP); if (cpEventMap == null) { throw AppUtility.getApplicationException(null, "event.req", ""); } CollectionProtocol collectionProtocol = createCollectionProtocolDomainObject(collectionProtocolBean); Collection collectionProtocolEventList = new LinkedHashSet(); Collection collectionProtocolEventBeanColl = cpEventMap.values(); if (collectionProtocolEventBeanColl != null) { Iterator cpEventIterator = collectionProtocolEventBeanColl.iterator(); while (cpEventIterator.hasNext()) { CollectionProtocolEventBean cpEventBean = (CollectionProtocolEventBean) cpEventIterator .next(); CollectionProtocolEvent collectionProtocolEvent = getCollectionProtocolEvent(cpEventBean); collectionProtocolEvent.setCollectionProtocol(collectionProtocol); collectionProtocolEventList.add(collectionProtocolEvent); } } collectionProtocol.setCollectionProtocolEventCollection(collectionProtocolEventList); return collectionProtocol; } /** * Creates collection protocol domain object from given collection protocol bean. * * @param cpBean the cp bean * * @return the collection protocol * * @throws Exception the exception */ private static CollectionProtocol createCollectionProtocolDomainObject( CollectionProtocolBean cpBean) throws Exception { CollectionProtocol collectionProtocol = new CollectionProtocol(); collectionProtocol.setId(cpBean.getIdentifier()); collectionProtocol.setSpecimenLabelFormat(cpBean.getLabelFormat()); collectionProtocol.setDerivativeLabelFormat(cpBean.getDerivativeLabelFormat()); collectionProtocol.setAliquotLabelFormat(cpBean.getAliquotLabelFormat()); collectionProtocol.setActivityStatus(cpBean.getActivityStatus()); collectionProtocol.setConsentsWaived(cpBean.isConsentWaived()); collectionProtocol.setIsEMPIEnabled(cpBean.getIsEMPIEnable()); collectionProtocol.setAliquotInSameContainer(cpBean.isAliqoutInSameContainer()); collectionProtocol.setConsentTierCollection(collectionProtocol .prepareConsentTierCollection(cpBean.getConsentValues())); Collection coordinatorCollection = new LinkedHashSet(); Collection<Site> siteCollection = new LinkedHashSet<Site>(); Collection<ClinicalDiagnosis> clinicalDiagnosisCollection = new LinkedHashSet<ClinicalDiagnosis>(); setCoordinatorColl(collectionProtocol, coordinatorCollection, cpBean); /**For Clinical Diagnosis Subset **/ setClinicalDiagnosis(collectionProtocol, clinicalDiagnosisCollection, cpBean); setSiteColl(collectionProtocol, siteCollection, cpBean); collectionProtocol.setDescriptionURL(cpBean.getDescriptionURL()); Integer enrollmentNo = null; try { enrollmentNo = Integer.valueOf(cpBean.getEnrollment()); } catch (NumberFormatException e) { CollectionProtocolUtil.LOGGER.error(e.getMessage(), e); enrollmentNo = Integer.valueOf(0); } collectionProtocol.setEnrollment(enrollmentNo); User principalInvestigator = new User(); principalInvestigator.setId(Long.valueOf(cpBean.getPrincipalInvestigatorId())); collectionProtocol.setPrincipalInvestigator(principalInvestigator); collectionProtocol.setShortTitle(cpBean.getShortTitle()); Date startDate = Utility.parseDate(cpBean.getStartDate(), Utility.datePattern(cpBean .getStartDate())); collectionProtocol.setStartDate(startDate); collectionProtocol.setTitle(cpBean.getTitle()); collectionProtocol.setUnsignedConsentDocumentURL(cpBean.getUnsignedConsentURLName()); collectionProtocol.setIrbIdentifier(cpBean.getIrbID()); collectionProtocol.setType(cpBean.getType()); collectionProtocol.setSequenceNumber(cpBean.getSequenceNumber()); collectionProtocol.setStudyCalendarEventPoint(cpBean.getStudyCalendarEventPoint()); if (cpBean.getParentCollectionProtocolId() != null && cpBean.getParentCollectionProtocolId() != 0 && !"".equals(cpBean.getParentCollectionProtocolId())) { collectionProtocol.setParentCollectionProtocol(getParentCollectionProtocol(cpBean .getParentCollectionProtocolId())); } //Ashraf: creating association collection from CP dashboard JSON string if (cpBean.getDashboardLabelJsonValue() != null) { collectionProtocol.setLabelSQLAssociationCollection(populateLabelSQLAssocColl(cpBean .getDashboardLabelJsonValue(), collectionProtocol)); } else { collectionProtocol.setLabelSQLAssociationCollection(new LinkedHashSet( new LabelSQLAssociationBizlogic().getLabelSQLAssocCollectionByCPId(cpBean .getIdentifier()))); } return collectionProtocol; } /** * This method will be called to return the CollectionProtocol. * * @param parentCollectionProtocolId : parentCollectionProtocolId. * * @return the collectionProtocol. * * @throws ApplicationException ApplicationException. */ public static CollectionProtocol getParentCollectionProtocol(Long parentCollectionProtocolId) throws ApplicationException { CollectionProtocol collectionProtocol = (CollectionProtocol) getObject( CollectionProtocol.class.getName(), parentCollectionProtocolId); return collectionProtocol; } /** * Sets the site coll. * * @param collectionProtocol the collection protocol * @param siteCollection the site collection * @param cpBean the cp bean */ private static void setSiteColl(CollectionProtocol collectionProtocol, Collection<Site> siteCollection, CollectionProtocolBean cpBean) { long[] siteArr = cpBean.getSiteIds(); if (siteArr != null) { for (int i = 0; i < siteArr.length; i++) { if (siteArr[i] != -1) { Site site = new Site(); site.setId(Long.valueOf(siteArr[i])); siteCollection.add(site); } } collectionProtocol.setSiteCollection(siteCollection); } } /** * Sets the coordinator coll. * * @param collectionProtocol the collection protocol * @param coordinatorCollection the coordinator collection * @param cpBean the cp bean */ private static void setCoordinatorColl(CollectionProtocol collectionProtocol, Collection coordinatorCollection, CollectionProtocolBean cpBean) { long[] coordinatorsArr = cpBean.getCoordinatorIds(); if (coordinatorsArr != null) { for (int i = 0; i < coordinatorsArr.length; i++) { if (coordinatorsArr[i] >= 1) { User coordinator = new User(); coordinator.setId(Long.valueOf(coordinatorsArr[i])); coordinatorCollection.add(coordinator); } } collectionProtocol.setCoordinatorCollection(coordinatorCollection); } } /** * Sets the clinical diagnosis. * * @param collectionProtocol the collection protocol * @param clinicalDiagnosis the clinical diagnosis * @param cpBean the cp bean */ private static void setClinicalDiagnosis(CollectionProtocol collectionProtocol, Collection clinicalDiagnosis, CollectionProtocolBean cpBean) { String[] clinicalDiagnosisArr = cpBean.getClinicalDiagnosis(); if (clinicalDiagnosisArr != null) { for (int i = 0; i < clinicalDiagnosisArr.length; i++) { if (!"".equals(clinicalDiagnosisArr[i])) { final ClinicalDiagnosis clinicalDiagnosisObj = new ClinicalDiagnosis(); clinicalDiagnosisObj.setName(clinicalDiagnosisArr[i]); clinicalDiagnosisObj.setCollectionProtocol(collectionProtocol); clinicalDiagnosis.add(clinicalDiagnosisObj); } } collectionProtocol.setClinicalDiagnosisCollection(clinicalDiagnosis); } } /** * This function used to create CollectionProtocolEvent domain object * from given CollectionProtocolEventBean Object. * * @param cpEventBean the cp event bean * * @return CollectionProtocolEvent domain object. * @throws ApplicationException */ private static CollectionProtocolEvent getCollectionProtocolEvent( CollectionProtocolEventBean cpEventBean) throws ApplicationException { CollectionProtocolEvent collectionProtocolEvent = new CollectionProtocolEvent(); collectionProtocolEvent.setClinicalStatus(cpEventBean.getClinicalStatus()); collectionProtocolEvent.setCollectionPointLabel(cpEventBean.getCollectionPointLabel()); collectionProtocolEvent .setStudyCalendarEventPoint(cpEventBean.getStudyCalenderEventPoint()); collectionProtocolEvent.setActivityStatus(Status.ACTIVITY_STATUS_ACTIVE.toString()); collectionProtocolEvent.setClinicalDiagnosis(cpEventBean.getClinicalDiagnosis()); if (cpEventBean.getId() == -1) { collectionProtocolEvent.setId(null); } else { collectionProtocolEvent.setId(Long.valueOf(cpEventBean.getId())); } if (cpEventBean.getDefaultSiteId() != null && cpEventBean.getDefaultSiteId() != 0) { Site defaultSite = (Site) getObject(Site.class.getName(), cpEventBean .getDefaultSiteId()); //defaultSite.setId(cpEventBean.getDefaultSiteId()); collectionProtocolEvent.setDefaultSite(defaultSite); } Collection specimenCollection = null; Map specimenMap = cpEventBean.getSpecimenRequirementbeanMap(); if (specimenMap != null && !specimenMap.isEmpty()) { specimenCollection = getReqSpecimens(specimenMap.values(), null, collectionProtocolEvent); } collectionProtocolEvent.setSpecimenRequirementCollection(specimenCollection); collectionProtocolEvent.setLabelFormat(cpEventBean.getLabelFormat()); return collectionProtocolEvent; } private static AbstractDomainObject getObject(String className, long identifier) throws ApplicationException { AbstractDomainObject domainObj = null; DAO dao = null; try { dao = AppUtility.openDAOSession(null); domainObj = (AbstractDomainObject) dao.retrieveById(className, identifier); } finally { AppUtility.closeDAOSession(dao); } return domainObj; } /** * creates collection of Specimen domain objects. * * @param specimenRequirementBeanColl the specimen requirement bean coll * @param parentSpecimen the parent specimen * @param cpEvent the cp event * * @return the req specimens */ public static Collection getReqSpecimens(Collection specimenRequirementBeanColl, SpecimenRequirement parentSpecimen, CollectionProtocolEvent cpEvent) { Collection<SpecimenRequirement> reqSpecimenCollection = new LinkedHashSet<SpecimenRequirement>(); Iterator iterator = specimenRequirementBeanColl.iterator(); while (iterator.hasNext()) { SpecimenRequirementBean specimenRequirementBean = (SpecimenRequirementBean) iterator .next(); SpecimenRequirement reqSpecimen = getSpecimenDomainObject(specimenRequirementBean); reqSpecimen.setParentSpecimen(parentSpecimen); if (parentSpecimen == null) { SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics(); long identifier = specimenRequirementBean.getSpecimenCharsId(); if (identifier != -1) { specimenCharacteristics.setId(Long.valueOf(identifier)); } specimenCharacteristics.setTissueSide(specimenRequirementBean.getTissueSide()); specimenCharacteristics.setTissueSite(specimenRequirementBean.getTissueSite()); reqSpecimen.setCollectionProtocolEvent(cpEvent); reqSpecimen.setSpecimenCharacteristics(specimenCharacteristics); //Collected and received events if (reqSpecimen.getId() == null) { setSpecimenEvents(reqSpecimen, specimenRequirementBean); } } else { reqSpecimen.setSpecimenCharacteristics(parentSpecimen.getSpecimenCharacteristics()); //bug no. 7489 //Collected and received events if (specimenRequirementBean.getCollectionEventContainer() != null && specimenRequirementBean.getReceivedEventReceivedQuality() != null) { if (reqSpecimen.getId() == null) { setSpecimenEvents(reqSpecimen, specimenRequirementBean); } } else { reqSpecimen.setSpecimenEventCollection(parentSpecimen .getSpecimenEventCollection()); } } reqSpecimen.setLineage(specimenRequirementBean.getLineage()); reqSpecimenCollection.add(reqSpecimen); Map aliquotColl = specimenRequirementBean.getAliquotSpecimenCollection(); Collection childSpecimens = new HashSet(); if (aliquotColl != null && !aliquotColl.isEmpty()) { Collection aliquotCollection = specimenRequirementBean .getAliquotSpecimenCollection().values(); childSpecimens = getReqSpecimens(aliquotCollection, reqSpecimen, cpEvent); reqSpecimenCollection.addAll(childSpecimens); } Map drivedColl = specimenRequirementBean.getDeriveSpecimenCollection(); if (drivedColl != null && !drivedColl.isEmpty()) { Collection derivedCollection = specimenRequirementBean .getDeriveSpecimenCollection().values(); Collection derivedSpecimens = getReqSpecimens(derivedCollection, reqSpecimen, cpEvent); if (childSpecimens == null || childSpecimens.isEmpty()) { childSpecimens = derivedSpecimens; } else { childSpecimens.addAll(derivedSpecimens); } reqSpecimenCollection.addAll(childSpecimens); } reqSpecimen.setChildSpecimenCollection(childSpecimens); } return reqSpecimenCollection; } /** * Sets the specimen events. * * @param reqSpecimen the req specimen * @param specimenRequirementBean the specimen requirement bean */ private static void setSpecimenEvents(SpecimenRequirement reqSpecimen, SpecimenRequirementBean specimenRequirementBean) { //seting collection event values Collection<SpecimenEventParameters> specimenEventCollection = new LinkedHashSet<SpecimenEventParameters>(); if (specimenRequirementBean.getCollectionEventContainer() != null) { CollectionEventParameters collectionEvent = new CollectionEventParameters(); collectionEvent.setCollectionProcedure(specimenRequirementBean .getCollectionEventCollectionProcedure()); collectionEvent.setContainer(specimenRequirementBean.getCollectionEventContainer()); User collectionEventUser = new User(); collectionEventUser.setId(Long.valueOf(specimenRequirementBean .getCollectionEventUserId())); collectionEvent.setUser(collectionEventUser); collectionEvent.setSpecimen(reqSpecimen); specimenEventCollection.add(collectionEvent); } //setting received event values if (specimenRequirementBean.getReceivedEventReceivedQuality() != null) { ReceivedEventParameters receivedEvent = new ReceivedEventParameters(); receivedEvent.setReceivedQuality(specimenRequirementBean .getReceivedEventReceivedQuality()); User receivedEventUser = new User(); receivedEventUser.setId(Long.valueOf(specimenRequirementBean.getReceivedEventUserId())); receivedEvent.setUser(receivedEventUser); receivedEvent.setSpecimen(reqSpecimen); specimenEventCollection.add(receivedEvent); } reqSpecimen.setSpecimenEventCollection(specimenEventCollection); } /** * creates specimen domain object from given specimen requirement bean. * * @param specimenRequirementBean the specimen requirement bean * * @return the specimen domain object */ private static SpecimenRequirement getSpecimenDomainObject( SpecimenRequirementBean specimenRequirementBean) { NewSpecimenForm form = new NewSpecimenForm(); form.setClassName(specimenRequirementBean.getClassName()); SpecimenRequirement reqSpecimen = null; try { if (form.getClassName().equals("Tissue")) { reqSpecimen = new TissueSpecimenRequirement(); } else if (form.getClassName().equals("Fluid")) { reqSpecimen = new FluidSpecimenRequirement(); } else if (form.getClassName().equals("Cell")) { reqSpecimen = new CellSpecimenRequirement(); } else if (form.getClassName().equals("Molecular")) { reqSpecimen = new MolecularSpecimenRequirement(); } } catch (Exception e1) { CollectionProtocolUtil.LOGGER.error("Error in setting Section " + "header Priorities" + e1.getMessage(), e1); return null; } if (specimenRequirementBean.getId() == -1) { reqSpecimen.setId(null); } else { reqSpecimen.setId(Long.valueOf(specimenRequirementBean.getId())); } reqSpecimen.setActivityStatus(Status.ACTIVITY_STATUS_ACTIVE.toString()); reqSpecimen.setInitialQuantity(new Double(specimenRequirementBean.getQuantity())); reqSpecimen.setLineage(specimenRequirementBean.getLineage()); reqSpecimen.setPathologicalStatus(specimenRequirementBean.getPathologicalStatus()); reqSpecimen.setSpecimenType(specimenRequirementBean.getType()); String storageType = specimenRequirementBean.getStorageContainerForSpecimen(); if (specimenRequirementBean.getClassName().equalsIgnoreCase(Constants.MOLECULAR)) { ((MolecularSpecimenRequirement) reqSpecimen) .setConcentrationInMicrogramPerMicroliter(new Double(specimenRequirementBean .getConcentration())); } reqSpecimen.setStorageType(storageType); reqSpecimen.setSpecimenClass(specimenRequirementBean.getClassName()); reqSpecimen.setLabelFormat(specimenRequirementBean.getLabelFormat()); return reqSpecimen; } /** * Gets the collection protocol for scg. * * @param identifier the identifier * * @return the collection protocol for scg * * @throws ApplicationException the application exception */ public static CollectionProtocol getCollectionProtocolForSCG(String identifier) throws ApplicationException { IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); CollectionProtocolBizLogic collectionProtocolBizLogic = (CollectionProtocolBizLogic) factory .getBizLogic(Constants.COLLECTION_PROTOCOL_FORM_ID); String sourceObjectName = SpecimenCollectionGroup.class.getName(); String[] whereColName = {"id"}; String[] whereColCond = {"="}; Object[] whereColVal = {Long.parseLong(identifier)}; String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol"}; List list = collectionProtocolBizLogic.retrieve(sourceObjectName, selectColumnName, whereColName, whereColCond, whereColVal, Constants.AND_JOIN_CONDITION); CollectionProtocol returnVal = null; if (list != null && !list.isEmpty()) { CollectionProtocol collectionProtocol = (CollectionProtocol) list.get(0); returnVal = collectionProtocol; } return returnVal; } //bug 8905 /** * This method is used to sort consents according to id. * * @param consentsMap the consents map * * @return sorted map */ public static Map sortConsentMap(Map consentsMap) { Set keys = consentsMap.keySet(); List<String> idList = new ArrayList<String>(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); idList.add(key); } Collections.sort(idList, new IdComparator()); Map idMap = new LinkedHashMap(); Iterator idIterator = idList.iterator(); while (idIterator.hasNext()) { String identifier = (String) idIterator.next(); idMap.put(identifier, consentsMap.get(identifier)); } return idMap; } /** * Update the Clinical Diagnosis value. * * @param request request * @param collectionProtocolBean collectionProtocolBean */ public static void updateClinicalDiagnosis(HttpServletRequest request, final CollectionProtocolBean collectionProtocolBean) { if (collectionProtocolBean != null) { Collection<NameValueBean> clinicalDiagnosisBean = new LinkedHashSet<NameValueBean>(); Locale locale = CommonServiceLocator.getInstance().getDefaultLocale(); Object[] clinicalDiagnosis = collectionProtocolBean.getClinicalDiagnosis(); if (clinicalDiagnosis != null) { for (int i = 0; i < clinicalDiagnosis.length; i++) { NameValueBean nvb = new NameValueBean(clinicalDiagnosis[i], clinicalDiagnosis[i]); nvb.getName().toLowerCase(locale); clinicalDiagnosisBean.add(nvb); } } Collection<NameValueBean> clinicalDiagnosisBeans = new ArrayList<NameValueBean>(); clinicalDiagnosisBeans.addAll(clinicalDiagnosisBean); request.setAttribute(edu.common.dynamicextensions.ui.util.Constants.SELECTED_VALUES, clinicalDiagnosisBeans); } } /** * returns the errors. * * @param request gives the error key. * * @return errors. */ public static ActionErrors getActionErrors(HttpServletRequest request) { ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY); if (errors == null) { errors = new ActionErrors(); } return errors; } /** * This method will return collectionProtocolId. * * @param specimenId - specimen id * @param dao - DAO obj * * @return collectionProtocolId - collectionProtocolId * * @throws BizLogicException - BizLogicException */ public static String getCPIdFromSpecimen(String specimenId, DAO dao) throws BizLogicException { String collectionProtocolId = ""; if (specimenId != null && !specimenId.trim().equals("")) { final Specimen specimen = new Specimen(); specimen.setId(Long.parseLong(specimenId)); try { final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); final NewSpecimenBizLogic newSpecimenBizLogic = (NewSpecimenBizLogic) factory .getBizLogic(edu.wustl.catissuecore.util.global.Constants.NEW_SPECIMEN_FORM_ID); collectionProtocolId = newSpecimenBizLogic.getObjectId(dao, specimen); if (collectionProtocolId != null && !collectionProtocolId.trim().equals("")) { collectionProtocolId = collectionProtocolId.split("_")[1]; } } catch (final ApplicationException appEx) { collectionProtocolId = ""; throw new BizLogicException(appEx.getErrorKey(), appEx, appEx.getMsgValues()); } } return collectionProtocolId; } /** * Converts the JSON string to for dashboard items to LableSQLAssociationCollection object * @param dashboardLabelJsonValue * @param cp * @return * @throws Exception */ public static Collection<LabelSQLAssociation> populateLabelSQLAssocColl( String dashboardLabelJsonValue, CollectionProtocol cp) throws Exception { JSONObject gridJson = new JSONObject(dashboardLabelJsonValue); JSONArray innerArray = gridJson.getJSONArray("row"); Collection<LabelSQLAssociation> labelSQLAssociationCollection = cp .getLabelSQLAssociationCollection();//retrieve labelSQL associations from CP List<LabelSQLAssociation> labelSQLAssociationList = new ArrayList<LabelSQLAssociation>(); for (int i = 0; i < innerArray.length(); i++) { JSONObject rowObject = innerArray.getJSONObject(i); LabelSQLAssociation labelSQLAssociation = new LabelSQLAssociation(); if (!"".equals(rowObject.get("assocId"))) { labelSQLAssociation.setId(rowObject.getLong("assocId")); } LabelSQL labelSQL = new LabelSQL(); labelSQL.setId(rowObject.getLong("labelId")); labelSQLAssociation.setLabelSQL(labelSQL); String userDefinedLabel = trim(rowObject.getString("userDefinedLabel")); //if none value defined for userdefinedlabel then assign null to it if ("".equals(userDefinedLabel)) { userDefinedLabel = null; } labelSQLAssociation.setUserDefinedLabel(userDefinedLabel); labelSQLAssociation.setLabelSQLCollectionProtocol(cp.getId()); labelSQLAssociation.setSeqOrder(rowObject.getInt("seqOrder")); labelSQLAssociationList.add(labelSQLAssociation); } if (!labelSQLAssociationList.isEmpty()) { if (labelSQLAssociationCollection != null)//check if collection contains items { Iterator iter = labelSQLAssociationCollection.iterator(); while (iter.hasNext()) { iter.next(); iter.remove();//Removing the items from collection } } else { //collection is empty hence creating new linkedhashset labelSQLAssociationCollection = new LinkedHashSet<LabelSQLAssociation>(); } labelSQLAssociationCollection.addAll(labelSQLAssociationList);//putting all values from association list } return labelSQLAssociationCollection; } /** * Trim. * * @param strValue the str value * * @return the string */ public static String trim(String strValue) { /*String returnValue = null; if (strValue != null) { returnValue = strValue.trim(); }*/ return ((strValue == null) ? null : strValue.trim()); } public static LinkedList<GenericSpecimen> getSpecimenList( Collection<GenericSpecimen> specimenColl) { final LinkedList<GenericSpecimen> specimenList = new LinkedList<GenericSpecimen>(); if (!specimenColl.isEmpty()) { specimenList.addAll(specimenColl); } return specimenList; } public static SpecimenRequirementBean duplicateSpeccimenRequirementBean( SpecimenRequirementBean oldBean, String uniqueIdentifier, int index) { final SpecimenRequirementBean specimenRequirementBean = new SpecimenRequirementBean(); if (oldBean.getLineage().equals(Constants.NEW_SPECIMEN)) { specimenRequirementBean .setParentName(Constants.ALIAS_SPECIMEN + "_" + uniqueIdentifier); specimenRequirementBean.setUniqueIdentifier(uniqueIdentifier + Constants.UNIQUE_IDENTIFIER_FOR_NEW_SPECIMEN + index); specimenRequirementBean.setDisplayName(Constants.ALIAS_SPECIMEN + "_" + uniqueIdentifier + Constants.UNIQUE_IDENTIFIER_FOR_NEW_SPECIMEN + index); } else if (oldBean.getLineage().equals(Constants.ALIQUOT)) { specimenRequirementBean.setUniqueIdentifier(uniqueIdentifier + Constants.UNIQUE_IDENTIFIER_FOR_ALIQUOT + index); specimenRequirementBean.setDisplayName(Constants.ALIAS_SPECIMEN + "_" + uniqueIdentifier + Constants.UNIQUE_IDENTIFIER_FOR_ALIQUOT + index); } else if (oldBean.getLineage().equals(Constants.DERIVED_SPECIMEN)) { specimenRequirementBean.setUniqueIdentifier(uniqueIdentifier + Constants.UNIQUE_IDENTIFIER_FOR_DERIVE + index); specimenRequirementBean.setDisplayName(Constants.ALIAS_SPECIMEN + "_" + uniqueIdentifier + Constants.UNIQUE_IDENTIFIER_FOR_DERIVE + index); } setSessionDataBean(specimenRequirementBean, oldBean); specimenRequirementBean.setLineage(oldBean.getLineage()); // Aliquot specimenRequirementBean.setNoOfAliquots(oldBean.getNoOfAliquots()); specimenRequirementBean.setLabelFormat(oldBean.getLabelFormat()); specimenRequirementBean.setLabelFormatForAliquot(oldBean.getLabelFormatForAliquot()); specimenRequirementBean.setQuantityPerAliquot(oldBean.getQuantityPerAliquot()); specimenRequirementBean.setStorageContainerForAliquotSpecimem(oldBean .getStorageContainerForAliquotSpecimem()); specimenRequirementBean.setNoOfDeriveSpecimen(oldBean.getNoOfDeriveSpecimen()); specimenRequirementBean.setDeriveSpecimen(oldBean.getDeriveSpecimen()); return specimenRequirementBean; } private static void setSessionDataBean(SpecimenRequirementBean newSpecimenRequirementBean, SpecimenRequirementBean oldSpecimenRequirementBean) { newSpecimenRequirementBean.setClassName(oldSpecimenRequirementBean.getClassName()); newSpecimenRequirementBean.setType(oldSpecimenRequirementBean.getType()); newSpecimenRequirementBean.setTissueSide(oldSpecimenRequirementBean.getTissueSide()); newSpecimenRequirementBean.setTissueSite(oldSpecimenRequirementBean.getTissueSite()); newSpecimenRequirementBean.setPathologicalStatus(oldSpecimenRequirementBean .getPathologicalStatus()); newSpecimenRequirementBean.setConcentration(oldSpecimenRequirementBean.getConcentration()); newSpecimenRequirementBean.setQuantity(oldSpecimenRequirementBean.getQuantity()); newSpecimenRequirementBean.setStorageContainerForSpecimen(oldSpecimenRequirementBean .getStorageContainerForSpecimen()); // Collected and received events newSpecimenRequirementBean.setCollectionEventUserId(oldSpecimenRequirementBean .getCollectionEventUserId()); newSpecimenRequirementBean.setReceivedEventUserId(oldSpecimenRequirementBean .getReceivedEventUserId()); newSpecimenRequirementBean.setCollectionEventContainer(oldSpecimenRequirementBean .getCollectionEventContainer()); newSpecimenRequirementBean.setReceivedEventReceivedQuality(oldSpecimenRequirementBean .getReceivedEventReceivedQuality()); newSpecimenRequirementBean.setCollectionEventCollectionProcedure(oldSpecimenRequirementBean .getCollectionEventCollectionProcedure()); } public static LinkedHashMap<String, GenericSpecimen> getSpecimenRequirementMap( String uniqueIdentifier, LinkedList<GenericSpecimen> specimenList) { LinkedHashMap<String, GenericSpecimen> specimenMap = new LinkedHashMap<String, GenericSpecimen>(); if (specimenList != null) { //Iterator<String> keyIterator = keySet.iterator(); Iterator<GenericSpecimen> specIterator = specimenList.iterator(); int specCounter = 0; int aliquoteCounter = 1; int derivativeCounter = 1; while (specIterator.hasNext()) { SpecimenRequirementBean oldSpecimen = (SpecimenRequirementBean) specIterator.next(); SpecimenRequirementBean specimen = new SpecimenRequirementBean(); if (oldSpecimen.getLineage().equals(Constants.NEW_SPECIMEN)) { specimen = CollectionProtocolUtil.duplicateSpeccimenRequirementBean( oldSpecimen, uniqueIdentifier, specCounter); specCounter++; } else if (oldSpecimen.getLineage().equals(Constants.ALIQUOT)) { specimen = CollectionProtocolUtil.duplicateSpeccimenRequirementBean( oldSpecimen, uniqueIdentifier, aliquoteCounter); aliquoteCounter++; } else { specimen = CollectionProtocolUtil.duplicateSpeccimenRequirementBean( oldSpecimen, uniqueIdentifier, derivativeCounter); derivativeCounter++; } specimen.setContainerId(null); if (specimen.getParentSpecimen() != null) { specimen.getParentSpecimen().setId(0L); } if (oldSpecimen.getAliquotSpecimenCollection() != null && !oldSpecimen.getAliquotSpecimenCollection().isEmpty()) { final LinkedList<GenericSpecimen> aliquoteList = CollectionProtocolUtil .getSpecimenList(oldSpecimen.getAliquotSpecimenCollection().values()); LinkedHashMap<String, GenericSpecimen> aliqMap = getSpecimenRequirementMap( specimen.getUniqueIdentifier(), aliquoteList); specimen.setAliquotSpecimenCollection(aliqMap); } if (oldSpecimen.getDeriveSpecimenCollection() != null && !oldSpecimen.getDeriveSpecimenCollection().isEmpty()) { final LinkedList<GenericSpecimen> derivativeList = CollectionProtocolUtil .getSpecimenList(oldSpecimen.getDeriveSpecimenCollection().values()); LinkedHashMap<String, GenericSpecimen> derivMap = getSpecimenRequirementMap( specimen.getUniqueIdentifier(), derivativeList); specimen.setDeriveSpecimenCollection(derivMap); } specimenMap.put(specimen.getUniqueIdentifier(), specimen); } } return specimenMap; } }
/* * $Log: PipeLine.java,v $ * Revision 1.61 2008-05-21 08:40:36 europe\L190409 * fixed pipeline output validation * * Revision 1.60 2008/02/15 14:05:08 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging * * Revision 1.59 2008/02/06 16:36:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added support for setting of transaction timeout * * Revision 1.58 2008/01/11 14:49:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed external pipe and pipeline executors * * Revision 1.57 2008/01/11 09:07:32 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * convert transaction management to Spring * * Revision 1.56 2007/12/27 16:01:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * avoid NPE for null pipeline results * * Revision 1.55 2007/12/17 08:49:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * input and output validation * * Revision 1.54 2007/12/10 10:04:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed commitOnState (rollback only, no exceptions) * added input/output validation * * Revision 1.53 2007/11/22 08:42:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * wrap exceptions * * Revision 1.52 2007/11/21 13:16:13 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * make commitOnState work * * Revision 1.51 2007/10/17 09:27:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restore setting of message and messageId in the pipelinesession * * Revision 1.50 2007/10/16 07:51:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed argument order in pipelineexecute * * Revision 1.49 2007/10/10 07:57:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * use configurable transactional executors * * Revision 1.48 2007/10/08 13:29:49 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed ArrayList to List where possible * * Revision 1.47 2007/09/27 12:53:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved warning * * Revision 1.46 2007/09/04 07:58:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * clearified exception message * * Revision 1.45 2007/07/17 15:09:08 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added list of pipes, to access them in order * * Revision 1.44 2007/06/21 07:05:24 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * optimized debug-logging * * Revision 1.43 2007/06/19 12:10:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * remove superfluous exception loggings * * Revision 1.42 2007/06/08 12:16:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * restored operation of commitOnState * * Revision 1.41 2007/06/07 15:15:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * set names of isolated threads * * Revision 1.40 2007/05/02 11:31:42 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added support for attribute 'active' * added support for attribute getInputFromFixedValue * * Revision 1.39 2007/05/01 14:08:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of PipeLine-exithandlers * * Revision 1.38 2007/02/12 13:44:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Logger from LogUtil * * Revision 1.37 2007/02/05 14:54:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fix bug in starting isolated thread * * Revision 1.36 2006/12/21 12:55:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fix bug in isolated call of Pipe * * Revision 1.35 2006/12/13 16:23:11 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed NPE * * Revision 1.34 2006/09/25 09:23:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed bug in PipeRunWrapper * * Revision 1.33 2006/09/18 14:05:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected transactionAttribute handling for Pipes * * Revision 1.32 2006/09/18 11:55:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * difference in debug of transactionAttributes of PipeLine and Pipes * * Revision 1.31 2006/09/14 15:06:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added getPipe() and getPipes() * * Revision 1.30 2006/09/14 12:12:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected javadoc * * Revision 1.29 2006/08/22 12:51:43 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * handling of preserveInput attribute of Pipes * * Revision 1.28 2006/08/22 07:49:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * introduction of transaction attribute handling * * Revision 1.27 2006/02/20 15:42:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * moved METT-support to single entry point for tracing * * Revision 1.26 2006/02/09 07:57:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * METT tracing support * * Revision 1.25 2005/11/02 09:06:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected logging * * Revision 1.24 2005/09/20 13:32:18 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added check for emtpy-named pipes * * Revision 1.23 2005/09/08 15:52:19 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * moved extra functionality to IExtendedPipe * * Revision 1.22 2005/09/07 15:27:32 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * implemented processing for getInputFromSessionKey and storeResultInSessionKey * * Revision 1.21 2005/09/05 07:06:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * separate logger for durationThreshold * * Revision 1.20 2005/09/01 08:53:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added logging of messages for which processing exceeds maxDuration * * Revision 1.19 2005/08/30 15:54:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected typos in logging-statements * * Revision 1.18 2005/08/25 15:42:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * prohibit defining pipes with the same name * * Revision 1.17 2005/07/19 12:23:11 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * cosmetic changes * * Revision 1.16 2005/07/05 10:49:59 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved exception handling obtaining usertransaction * * Revision 1.15 2005/06/13 12:52:22 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * prepare for nested pipelines * * Revision 1.14 2005/02/10 07:49:00 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed clearing of pipelinesession a start of pipeline * * Revision 1.13 2005/01/13 08:55:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Make threadContext-attributes available in PipeLineSession * * Revision 1.12 2004/08/19 09:07:02 unknown <unknown@ibissource.org> * Add not-null validation for message * * Revision 1.11 2004/07/20 13:04:45 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Corrected erroneous pipe run statistics (yet another time) * * Revision 1.10 2004/07/05 09:54:44 Johan Verrips <johan.verrips@ibissource.org> * Improved errorhandling mechanism: when a PipeRunException occured, transactions where still committed * * Revision 1.9 2004/04/28 14:32:42 Johan Verrips <johan.verrips@ibissource.org> * Corrected erroneous pipe run statistics * * Revision 1.8 2004/04/06 12:43:14 Johan Verrips <johan.verrips@ibissource.org> * added CommitOnState * * Revision 1.7 2004/03/31 12:04:20 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed javadoc * * Revision 1.6 2004/03/30 07:29:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.5 2004/03/26 10:42:50 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * * Revision 1.4 2004/03/24 08:29:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed String 'adapterName' to Adapter 'adapter' * enabled XA transactions * */ package nl.nn.adapterframework.core; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.JtaUtil; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.Misc; import nl.nn.adapterframework.util.Semaphore; import nl.nn.adapterframework.util.SpringTxManagerProxy; import nl.nn.adapterframework.util.StatisticsKeeper; import nl.nn.adapterframework.util.TracingUtil; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; public class PipeLine { public static final String version = "$RCSfile: PipeLine.java,v $ $Revision: 1.61 $ $Date: 2008-05-21 08:40:36 $"; private Logger log = LogUtil.getLogger(this); private Logger durationLog = LogUtil.getLogger("LongDurationMessages"); private Adapter adapter; // for transaction managing private INamedObject owner; // for logging purposes private Hashtable pipeStatistics = new Hashtable(); private Hashtable pipeWaitingStatistics = new Hashtable(); private Hashtable globalForwards = new Hashtable(); private String firstPipe; private int transactionAttribute=TransactionDefinition.PROPAGATION_SUPPORTS; private int transactionTimeout=0; private IPipe inputValidator=null; private IPipe outputValidator=null; private TransactionDefinition txDef=null; private PlatformTransactionManager txManager; private Hashtable pipesByName=new Hashtable(); private List pipes=new ArrayList(); // set of exits paths with their state private Hashtable pipeLineExits=new Hashtable(); private Hashtable pipeThreadCounts=new Hashtable(); private String commitOnState="success"; // exit state on which receiver will commit XA transactions private List exitHandlers = new ArrayList(); /** * Register an Pipe at this pipeline. * The name is also put in the globalForwards table (with * forward-name=pipename and forward-path=pipename, so that * pipe can look for a specific pipe-name. If already a globalForward * exists under that name, the pipe is NOT added, allowing globalForwards * to prevail. * @see nl.nn.adapterframework.pipes.AbstractPipe **/ public void addPipe(IPipe pipe) throws ConfigurationException { if (pipe==null) { throw new ConfigurationException("pipe to be added is null, pipelineTable size ["+pipesByName.size()+"]"); } if (pipe instanceof IExtendedPipe && !((IExtendedPipe)pipe).isActive()) { log.debug("Pipe [" + pipe.getName() + "] is not active, therefore not included in configuration"); return; } String name=pipe.getName(); if (StringUtils.isEmpty(name)) { throw new ConfigurationException("pipe ["+pipe.getClass().getName()+"] to be added has no name, pipelineTable size ["+pipesByName.size()+"]"); } IPipe current=getPipe(name); if (current!=null) { throw new ConfigurationException("pipe ["+name+"] defined more then once"); } pipesByName.put(name, pipe); pipes.add(pipe); pipeStatistics.put(name, new StatisticsKeeper(name)); if (pipe.getMaxThreads() > 0) { pipeWaitingStatistics.put(name, new StatisticsKeeper(name)); } log.debug("added pipe [" + pipe.toString() + "]"); if (globalForwards.get(name) == null) { PipeForward pw = new PipeForward(); pw.setName(name); pw.setPath(name); registerForward(pw); } else { log.info("already had a pipeForward with name ["+ name+ "] skipping the implicit one to Pipe ["+ pipe.getName()+ "]"); } } public IPipe getPipe(String pipeName) { return (IPipe)pipesByName.get(pipeName); } public IPipe getPipe(int index) { return (IPipe)pipes.get(index); } public List getPipes() { return pipes; } public void registerExitHandler(IPipeLineExitHandler exitHandler) { exitHandlers.add(exitHandler); log.info("registered exithandler ["+exitHandler.getName()+"]"); } /** * Configures the pipes of this Pipeline and does some basic checks. It also * registers the <code>PipeLineSession</code> object at the pipes. * @see IPipe */ public void configurePipes() throws ConfigurationException { for (int i=0; i<pipes.size(); i++) { IPipe pipe=getPipe(i); String pipeName=pipe.getName(); log.debug("Pipeline of ["+owner.getName()+"] configuring "+pipeName); // register the global forwards at the Pipes // the pipe will take care that if a local, pipe-specific // forward is defined, it is not overwritten by the globals Enumeration globalForwardNames=globalForwards.keys(); while (globalForwardNames.hasMoreElements()) { String gfName=(String)globalForwardNames.nextElement(); PipeForward pipeForward= (PipeForward) globalForwards.get(gfName); pipe.registerForward(pipeForward); } if (pipe instanceof IExtendedPipe) { IExtendedPipe epipe=(IExtendedPipe)pipe; epipe.configure(this); } else { pipe.configure(); } if (log.isDebugEnabled()) log.debug("Pipeline of ["+owner.getName()+"]: Pipe ["+pipeName+"] successfully configured: ["+pipe.toString()+"]"); } if (pipeLineExits.size()<1) { throw new ConfigurationException("no PipeLine Exits specified"); } if (this.firstPipe==null) { throw new ConfigurationException("no firstPipe defined"); } if (getPipe(firstPipe)==null) { throw new ConfigurationException("no pipe found for firstPipe ["+firstPipe+"]"); } if (getInputValidator()!=null) { PipeForward pf = new PipeForward(); pf.setName("success"); getInputValidator().registerForward(pf); getInputValidator().setName("inputValidator of "+owner.getName()); getInputValidator().configure(); } if (getOutputValidator()!=null) { PipeForward pf = new PipeForward(); pf.setName("success"); getOutputValidator().registerForward(pf); getOutputValidator().setName("outputValidator of "+owner.getName()); getOutputValidator().configure(); } int txOption = this.getTransactionAttributeNum(); if (log.isDebugEnabled()) log.debug("creating TransactionDefinition for transactionAttribute ["+getTransactionAttribute()+"], timeout ["+getTransactionTimeout()+"]"); txDef = SpringTxManagerProxy.getTransactionDefinition(txOption,getTransactionTimeout()); log.debug("Pipeline of ["+owner.getName()+"] successfully configured"); } /** * @return the number of pipes in the pipeline */ public int getPipeLineSize(){ return pipesByName.size(); } /** * @return a Hashtable with in the key the pipenames and in the * value a {@link StatisticsKeeper} object with the statistics */ public Hashtable getPipeStatistics(){ return pipeStatistics; } /** * @return a Hashtable with in the key the pipenames and in the * value a {@link StatisticsKeeper} object with the statistics */ public Hashtable getPipeWaitingStatistics(){ return pipeWaitingStatistics; } private Semaphore getSemaphore(IPipe pipeToRun) { int maxThreads; maxThreads = pipeToRun.getMaxThreads(); if (maxThreads > 0) { Semaphore s; synchronized (pipeThreadCounts) { if (pipeThreadCounts.containsKey(pipeToRun)) { s = (Semaphore) pipeThreadCounts.get(pipeToRun); } else { s = new Semaphore(maxThreads); pipeThreadCounts.put(pipeToRun, s); } } return s; } return null; } /** * The <code>process</code> method does the processing of a message.<br/> * It retrieves the first pipe to execute from the <code>firstPipe</code field, * the call results in a PipRunResult, containing the next pipe to activate. * While processing the process method keeps statistics. * @param message The message as received from the Listener * @param messageId A unique id for this message, used for logging purposes. * @return the result of the processing. * @throws PipeRunException when something went wrong in the pipes. */ public PipeLineResult process(String messageId, String message, PipeLineSession pipeLineSession) throws PipeRunException { if (pipeLineSession==null) { pipeLineSession= new PipeLineSession(); } // reset the PipeLineSession and store the message and its id in the session if (messageId==null) { messageId=Misc.createSimpleUUID(); log.error("null value for messageId, setting to ["+messageId+"]"); } if (message == null) { throw new PipeRunException(null, "Pipeline of adapter ["+ owner.getName()+"] received null message"); } // store message and messageId in the pipeLineSession pipeLineSession.set(message, messageId); // boolean compatible; // if (log.isDebugEnabled()) log.debug("evaluating transaction status ["+JtaUtil.displayTransactionStatus()+"], transaction attribute ["+getTransactionAttribute()+"], messageId ["+messageId+"]"); // try { // compatible=JtaUtil.transactionStateCompatible(getTransactionAttributeNum()); // } catch (Exception t) { // throw new PipeRunException(null,"exception evaluating transaction status, transaction attribute ["+getTransactionAttribute()+"], messageId ["+messageId+"]",t); // if (!compatible) { // throw new PipeRunException(null,"transaction state ["+JtaUtil.displayTransactionStatus()+"] not compatible with transaction attribute ["+getTransactionAttribute()+"], messageId ["+messageId+"]"); if (log.isDebugEnabled()) log.debug("PipeLine transactionAttribute ["+getTransactionAttribute()+"]"); try { return runPipeLineObeyingTransactionAttribute( messageId, message, pipeLineSession); } catch (RuntimeException e) { throw new PipeRunException(null, "RuntimeException calling PipeLine with tx attribute [" + getTransactionAttribute() + "]", e); } } private PipeLineResult runPipeLineObeyingTransactionAttribute(String messageId, String message, PipeLineSession session) throws PipeRunException { if (log.isDebugEnabled()) log.debug("runPipeLineObeyingTransactionAttribute with transactionAttribute ["+getTransactionAttribute()+"], timeout ["+getTransactionTimeout()+"]"); TransactionStatus txStatus = txManager.getTransaction(txDef); try { return processPipeLine(messageId, message, session, txStatus); } catch (Throwable t) { log.debug("setting RollBackOnly for pipeline after catching exception"); txStatus.setRollbackOnly(); if (t instanceof Error) { throw (Error)t; } else if (t instanceof RuntimeException) { throw (RuntimeException)t; } else if (t instanceof PipeRunException) { throw (PipeRunException)t; } else { throw new PipeRunException(null, "Caught unknown checked exception", t); } } finally { if (log.isDebugEnabled()) log.debug("Performing commit/rollback for pipeline on transaction [" + txStatus+"]"); txManager.commit(txStatus); } } private PipeRunResult runPipeObeyingTransactionAttribute(IPipe pipe, Object message, PipeLineSession session) throws PipeRunException { int txOption; int txTimeout=0; if (pipe instanceof HasTransactionAttribute) { HasTransactionAttribute taPipe = (HasTransactionAttribute) pipe; txOption = taPipe.getTransactionAttributeNum(); txTimeout= taPipe.getTransactionTimeout(); if (log.isDebugEnabled()) log.debug("runPipeObeyingTransactionAttribute for pipe ["+pipe.getName()+"] with transactionAttribute ["+taPipe.getTransactionAttribute()+"]"); } else { txOption = TransactionDefinition.PROPAGATION_SUPPORTS; if (log.isDebugEnabled()) log.debug("runPipeObeyingTransactionAttribute for pipe ["+pipe.getName()+"] with default transaction attribute (supports)"); } TransactionStatus txStatus = txManager.getTransaction(SpringTxManagerProxy.getTransactionDefinition(txOption,txTimeout)); if (log.isDebugEnabled() && txStatus.isNewTransaction()) { log.debug("Pipeline created new transaction, timeout ["+(txTimeout==0?"system default(=120s)":""+txTimeout)+"]"); } try { return pipe.doPipe(message, session); } catch (Throwable t) { log.debug("setting RollBackOnly for pipe [" + pipe.getName()+"] after catching exception"); txStatus.setRollbackOnly(); if (t instanceof Error) { throw (Error)t; } else if (t instanceof RuntimeException) { throw (RuntimeException)t; } else if (t instanceof PipeRunException) { throw (PipeRunException)t; } else { throw new PipeRunException(pipe, "Caught unknown checked exception", t); } } finally { if (log.isDebugEnabled()) log.debug("Performing commit/rollback for pipe ["+pipe.getName()+"] on transaction [" + txStatus+"]"); txManager.commit(txStatus); } } /** * Run a PipeLine, without observing transaction status of the PipeLine. * * This method is meant to be executed from the IPipeLineExecutor * implementation. * * @param messageId * @param message * @param pipeLineSession * @return * @throws PipeRunException */ public PipeLineResult processPipeLine(String messageId, String message, PipeLineSession pipeLineSession, TransactionStatus txStatus) throws PipeRunException { // Object is the object that is passed to and returned from Pipes Object object = (Object) message; Object preservedObject = object; PipeRunResult pipeRunResult; // the PipeLineResult PipeLineResult pipeLineResult=new PipeLineResult(); // ready indicates wether the pipeline processing is complete boolean ready=false; // get the first pipe to run IPipe pipeToRun = getPipe(firstPipe); IPipe inputValidator = getInputValidator(); if (inputValidator!=null) { PipeRunResult validationResult = inputValidator.doPipe(message,pipeLineSession); if (validationResult!=null && !validationResult.getPipeForward().getName().equals("success")) { PipeForward validationForward=validationResult.getPipeForward(); if (validationForward.getPath()==null) { throw new PipeRunException(pipeToRun,"forward ["+validationForward.getName()+"] of inputValidator has emtpy forward path"); } log.warn("setting first pipe to ["+validationForward.getPath()+"] due to validation fault"); pipeToRun = getPipe(validationForward.getPath()); if (pipeToRun==null) { throw new PipeRunException(pipeToRun,"forward ["+validationForward.getName()+"], path ["+validationForward.getPath()+"] does not correspond to a pipe"); } } } boolean outputValidated=false; try { while (!ready){ IExtendedPipe pe=null; if (pipeToRun instanceof IExtendedPipe) { pe = (IExtendedPipe)pipeToRun; } TracingUtil.beforeEvent(pipeToRun); long pipeStartTime= System.currentTimeMillis(); if (log.isDebugEnabled()){ // for performance reasons StringBuffer sb=new StringBuffer(); String ownerName=owner==null?"<null>":owner.getName(); String pipeToRunName=pipeToRun==null?"<null>":pipeToRun.getName(); sb.append("Pipeline of adapter ["+ownerName+"] messageId ["+messageId+"] is about to call pipe ["+ pipeToRunName+"]"); if (AppConstants.getInstance().getProperty("log.logIntermediaryResults")!=null) { if (AppConstants.getInstance().getProperty("log.logIntermediaryResults").equalsIgnoreCase("true")) { sb.append(" current result ["+ object +"] "); } } log.debug(sb.toString()); } // start it long pipeDuration = -1; if (pe!=null) { if (StringUtils.isNotEmpty(pe.getGetInputFromSessionKey())) { if (log.isDebugEnabled()) log.debug("Pipeline of adapter ["+owner.getName()+"] replacing input for pipe ["+pe.getName()+"] with contents of sessionKey ["+pe.getGetInputFromSessionKey()+"]"); object=pipeLineSession.get(pe.getGetInputFromSessionKey()); } if (StringUtils.isNotEmpty(pe.getGetInputFromFixedValue())) { if (log.isDebugEnabled()) log.debug("Pipeline of adapter ["+owner.getName()+"] replacing input for pipe ["+pe.getName()+"] with fixed value ["+pe.getGetInputFromFixedValue()+"]"); object=pe.getGetInputFromFixedValue(); } } try { Semaphore s = getSemaphore(pipeToRun); if (s != null) { long waitingDuration = 0; try { // keep waiting statistics for thread-limited pipes long startWaiting = System.currentTimeMillis(); s.acquire(); waitingDuration = System.currentTimeMillis() - startWaiting; StatisticsKeeper sk = (StatisticsKeeper) pipeWaitingStatistics.get(pipeToRun.getName()); sk.addValue(waitingDuration); try { pipeRunResult = runPipeObeyingTransactionAttribute(pipeToRun,object, pipeLineSession); } catch (PipeRunException e) { throw e; } catch (Throwable t) { throw new PipeRunException(pipeToRun, "caught exception", t); } finally { long pipeEndTime = System.currentTimeMillis(); pipeDuration = pipeEndTime - pipeStartTime - waitingDuration; sk = (StatisticsKeeper) pipeStatistics.get(pipeToRun.getName()); sk.addValue(pipeDuration); } } catch (InterruptedException e) { throw new PipeRunException(pipeToRun, "Interrupted waiting for pipe", e); } finally { s.release(); } } else { //no restrictions on the maximum number of threads (s==null) try { pipeRunResult = runPipeObeyingTransactionAttribute(pipeToRun,object, pipeLineSession); } catch (PipeRunException e) { throw e; } catch (Throwable t) { throw new PipeRunException(pipeToRun, "caught exception", t); } finally { long pipeEndTime = System.currentTimeMillis(); pipeDuration = pipeEndTime - pipeStartTime; StatisticsKeeper sk = (StatisticsKeeper) pipeStatistics.get(pipeToRun.getName()); sk.addValue(pipeDuration); } } if (pe !=null) { if (pipeRunResult!=null && StringUtils.isNotEmpty(pe.getStoreResultInSessionKey())) { if (log.isDebugEnabled()) log.debug("Pipeline of adapter ["+owner.getName()+"] storing result for pipe ["+pe.getName()+"] under sessionKey ["+pe.getStoreResultInSessionKey()+"]"); pipeLineSession.put(pe.getStoreResultInSessionKey(),pipeRunResult.getResult()); } if (pe.isPreserveInput()) { pipeRunResult.setResult(preservedObject); } } } catch (PipeRunException pre) { TracingUtil.exceptionEvent(pipeToRun); throw pre; } catch (RuntimeException re) { TracingUtil.exceptionEvent(pipeToRun); throw new PipeRunException(pipeToRun, "Uncaught runtime exception running pipe '" + (pipeToRun==null?"null":pipeToRun.getName()) + "'", re); } finally { TracingUtil.afterEvent(pipeToRun); if (pe!=null) { if (pe.getDurationThreshold() >= 0 && pipeDuration > pe.getDurationThreshold()) { durationLog.info("Pipe ["+pe.getName()+"] of ["+owner.getName()+"] duration ["+pipeDuration+"] ms exceeds max ["+ pe.getDurationThreshold()+ "], message ["+object+"]"); } } } if (pipeRunResult==null){ throw new PipeRunException(pipeToRun, "Pipeline of ["+owner.getName()+"] received null result from pipe ["+pipeToRun.getName()+"]d"); } object=pipeRunResult.getResult(); preservedObject=object; PipeForward pipeForward=pipeRunResult.getPipeForward(); if (pipeForward==null){ throw new PipeRunException(pipeToRun, "Pipeline of ["+owner.getName()+"] received result from pipe ["+pipeToRun.getName()+"] without a pipeForward"); } // get the next pipe to run String nextPath=pipeForward.getPath(); if ((null==nextPath) || (nextPath.length()==0)){ throw new PipeRunException(pipeToRun, "Pipeline of ["+owner.getName()+"] got an path that equals null or has a zero-length value from pipe ["+pipeToRun.getName()+"]. Check the configuration, probably forwards are not defined for this pipe."); } PipeLineExit plExit=(PipeLineExit)pipeLineExits.get(nextPath); if (null!=plExit){ IPipe outputValidator = getOutputValidator(); if (outputValidator !=null && !outputValidated) { outputValidated=true; log.debug("validating PipeLineResult"); PipeRunResult validationResult = outputValidator.doPipe(object,pipeLineSession); if (validationResult!=null && !validationResult.getPipeForward().getName().equals("success")) { PipeForward validationForward=validationResult.getPipeForward(); if (validationForward.getPath()==null) { throw new PipeRunException(pipeToRun,"forward ["+validationForward.getName()+"] of outputValidator has emtpy forward path"); } log.warn("setting next pipe to ["+validationForward.getPath()+"] due to validation fault"); pipeToRun = getPipe(validationForward.getPath()); if (pipeToRun==null) { throw new PipeRunException(pipeToRun,"forward ["+validationForward.getName()+"], path ["+validationForward.getPath()+"] does not correspond to a pipe"); } } else { log.debug("validation succeeded"); ready=true; } } else { ready=true; } if (ready) { String state=plExit.getState(); pipeLineResult.setState(state); if (object!=null) { pipeLineResult.setResult(object.toString()); } else { pipeLineResult.setResult(null); } ready=true; if (log.isDebugEnabled()){ // for performance reasons log.debug("Pipeline of adapter ["+ owner.getName()+ "] finished processing messageId ["+messageId+"] result: ["+ object.toString()+ "] with exit-state ["+state+"]"); } } } else { pipeToRun=getPipe(pipeForward.getPath()); if (pipeToRun==null) { throw new PipeRunException(null, "Pipeline of adapter ["+ owner.getName()+"] got an erroneous definition. Pipe to execute ["+pipeForward.getPath()+ "] is not defined."); } } } } finally { for (int i=0; i<exitHandlers.size(); i++) { IPipeLineExitHandler exitHandler = (IPipeLineExitHandler)exitHandlers.get(i); try { if (log.isDebugEnabled()) log.debug("processing ExitHandler ["+exitHandler.getName()+"]"); exitHandler.atEndOfPipeLine(messageId,pipeLineResult,pipeLineSession); } catch (Throwable t) { log.warn("Caught Exception processing ExitHandler ["+exitHandler.getName()+"]",t); } } } boolean mustRollback=false; if (pipeLineResult==null) { mustRollback=true; log.warn("Pipeline received null result for messageId ["+messageId+"], transaction (when present and active) will be rolled back"); } else { if (StringUtils.isNotEmpty(getCommitOnState()) && !getCommitOnState().equalsIgnoreCase(pipeLineResult.getState())) { mustRollback=true; log.warn("Pipeline result state ["+pipeLineResult.getState()+"] for messageId ["+messageId+"] is not equal to commitOnState ["+getCommitOnState()+"], transaction (when present and active) will be rolled back"); } } if (mustRollback) { try { txStatus.setRollbackOnly(); } catch (Exception e) { throw new PipeRunException(null,"Could not set RollBackOnly",e); } } return pipeLineResult; } /** * Register global forwards. */ public void registerForward(PipeForward forward){ globalForwards.put(forward.getName(), forward); log.debug("registered global PipeForward "+forward.toString()); } public void registerPipeLineExit(PipeLineExit exit) { pipeLineExits.put(exit.getPath(), exit); } /** * Register the adapterName of this Pipelineprocessor. * @param adapterName */ public void setAdapter(Adapter adapter) { this.adapter = adapter; setOwner(adapter); } public void setOwner(INamedObject owner) { this.owner = owner; } /** * The indicator for the end of the processing, with default state "undefined". * @deprecated since v 3.2 this functionality is superseded by the use of {@link nl.nn.adapterframework.core.PipeLineExit PipeLineExits}. * @see PipeLineExit */ public void setEndPath(String endPath){ PipeLineExit te=new PipeLineExit(); te.setPath(endPath); te.setState("undefined"); registerPipeLineExit(te); } /** * set the name of the first pipe to execute when a message is to be * processed * @param pipeName the name of the pipe * @see nl.nn.adapterframework.pipes.AbstractPipe */ public void setFirstPipe(String pipeName){ firstPipe=pipeName; } public void start() throws PipeStartException { log.info("Pipeline of ["+owner.getName()+"] is starting pipeline"); for (int i=0; i<pipes.size(); i++) { IPipe pipe = getPipe(i); String pipeName = pipe.getName(); log.debug("Pipeline of ["+owner.getName()+"] starting pipe [" + pipeName+"]"); pipe.start(); log.debug("Pipeline of ["+owner.getName()+"] successfully started pipe [" + pipeName + "]"); } log.info("Pipeline of ["+owner.getName()+"] is successfully started pipeline"); } /** * Close the pipeline. This will call the <code>stop()</code> method * of all registered <code>Pipes</code> * @see IPipe#stop */ public void stop() { log.info("Pipeline of ["+owner.getName()+"] is closing pipeline"); for (int i=0; i<pipes.size(); i++) { IPipe pipe = getPipe(i); String pipeName = pipe.getName(); log.debug("Pipeline of ["+owner.getName()+"] is stopping [" + pipeName+"]"); pipe.stop(); log.debug("Pipeline of ["+owner.getName()+"] successfully stopped pipe [" + pipeName + "]"); } log.debug("Pipeline of ["+owner.getName()+"] successfully closed pipeline"); } /** * * @return an enumeration of all pipenames in the pipeline and the * startpipe and endpath * @see #setEndPath * @see #setFirstPipe */ public String toString(){ String result=""; result+="[ownerName="+(owner==null ? "-none-" : owner.getName())+"]"; result+="[adapterName="+(adapter==null ? "-none-" : adapter.getName())+"]"; result+="[startPipe="+firstPipe+"]"; // result+="[transacted="+transacted+"]"; result+="[transactionAttribute="+getTransactionAttribute()+"]"; for (int i=0; i<pipes.size(); i++) { result+="pipe"+i+"=["+getPipe(i).getName()+"]"; } Enumeration exitKeys=pipeLineExits.keys(); while (exitKeys.hasMoreElements()){ String exitPath=(String)exitKeys.nextElement(); PipeLineExit pe=(PipeLineExit)pipeLineExits.get(exitPath); result+="[path:"+pe.getPath()+" state:"+pe.getState()+"]"; } return result; } // public boolean isTransacted() { // return transacted; public void setTransacted(boolean transacted) { // this.transacted = transacted; if (transacted) { log.warn("implementing setting of transacted=true as transactionAttribute=Required"); setTransactionAttributeNum(TransactionDefinition.PROPAGATION_REQUIRED); } else { log.warn("implementing setting of transacted=false as transactionAttribute=Supports"); setTransactionAttributeNum(TransactionDefinition.PROPAGATION_SUPPORTS); } } /** * the exit state of the pipeline on which the receiver will commit the transaction. */ public void setCommitOnState(String string) { commitOnState = string; } public String getCommitOnState() { return commitOnState; } public void setTransactionAttribute(String attribute) throws ConfigurationException { transactionAttribute = JtaUtil.getTransactionAttributeNum(attribute); if (transactionAttribute<0) { throw new ConfigurationException("illegal value for transactionAttribute ["+attribute+"]"); } } public String getTransactionAttribute() { return JtaUtil.getTransactionAttributeString(transactionAttribute); } public void setTransactionAttributeNum(int i) { transactionAttribute = i; } public int getTransactionAttributeNum() { return transactionAttribute; } public void setInputValidator(IPipe inputValidator) { // if (inputValidator.isActive()) { this.inputValidator = inputValidator; } public IPipe getInputValidator() { return inputValidator; } public void setOutputValidator(IPipe outputValidator) { // if (outputValidator.isActive()) { this.outputValidator = outputValidator; } public IPipe getOutputValidator() { return outputValidator; } public void setTxManager(PlatformTransactionManager txManager) { this.txManager = txManager; } public PlatformTransactionManager getTxManager() { return txManager; } public void setTransactionTimeout(int i) { transactionTimeout = i; } public int getTransactionTimeout() { return transactionTimeout; } }
package net.neevek.android.widget; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.*; import android.view.animation.DecelerateInterpolator; import android.widget.*; /** * @author neevek <i at neevek.net> * @version v1.0.0 finished on Nov. 24, 2013 (a rainy Sunday in GuangZhou) * @version v1.0.3 finished at 2:49 a.m. on Dec. 5, 2013 * * This class implements the bounce effect & pull-to-refresh feature for * ListView(the implementation can also be applied to ExpandableListView). * * For the bounce effect, the implementation simply intercepts touch events * and detects if the scrolling has reached the top or bottom edge, if so, we * call scrollTo() to scroll the entire the ListView off the screen, and then * with a Scroller, we compute the Y scroll positions and create a smooth * bounce effect. * * For pull-to-refresh, the implementation uses a header view which implements * the PullToRefreshCallback interface as the indicator view for displaying * "Pull to refresh", "Release to refresh", "Loading..." and an arrow image. * Of course, you can implement PullToRefreshCallback and write your own * PullToRefreshHeaderView, as long as you follow some requirements for * the layout of the header view, take the default PullToRefreshHeaderView * as a reference. * * NOTE: If you do not want the pull-to-refresh feature, you can still use * OverScrollListView, in that case, OverScrollListView only offers * you the bounce effect, and that is why it has the name. just remember * not to call setPullToRefreshHeaderView() */ public class OverScrollListView extends ListView { private final static int DEFAULT_MAX_OVER_SCROLL_DURATION = 350; // boucing for a normal touch scroll gesture(happens right after the finger leaves the screen) private Scroller mScroller; private float mLastY; private boolean mIsTouching; private boolean mIsBeingTouchScrolled; // a threshold to tell whether the user is touch-scrolling private int mTouchSlop; private int mMinimumVelocity; private int mMaximumVelocity; // the top-level layout of the header view private PullToRefreshCallback mOrigHeaderView; // the layout, of which we will do adjust the height, and on which // we call requestLayout() to cause the view hierarchy to be redrawn private View mHeaderView; // for convenient adjustment of the header view height private ViewGroup.LayoutParams mHeaderViewLayoutParams; // the original height of the header view private int mHeaderViewHeight; // user of this pull-to-refresh ListView certainly will register a // a listener, which will be called when a "refresh" action should // be initiated. private OnRefreshListener mOnRefreshListener; private boolean mIsRefreshing; // is finishRefreshing() has just been called? private boolean mCancellingRefreshing; private PullToLoadMoreCallback mSavedFooterView; private PullToLoadMoreCallback mFooterView; private boolean mIsLoadingMore; private OnLoadMoreListener mOnLoadMoreListener; private int mLoadingMorePullDistanceThreshold; private float mScreenDensity; public OverScrollListView(Context context) { super(context); init(context); } public OverScrollListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public OverScrollListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { mScreenDensity = context.getResources().getDisplayMetrics().density; mLoadingMorePullDistanceThreshold = (int)(mScreenDensity * 50); mScroller = new Scroller(context, new DecelerateInterpolator(1.3f)); // on Android 2.3.3, disabling overscroll makes ListView behave weirdly if (Build.VERSION.SDK_INT > 10) { // disable the glow effect at the edges when overscrolling. setOverScrollMode(OVER_SCROLL_NEVER); } final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); } public void setPullToRefreshHeaderView(View headerView) { if (!(headerView instanceof PullToRefreshCallback)) { throw new IllegalArgumentException("Pull-to-refresh header view must implement PullToRefreshCallback"); } mOrigHeaderView = (PullToRefreshCallback)headerView; addHeaderView(headerView); } @Override public void addHeaderView(View v, Object data, boolean isSelectable) { if (v instanceof ViewGroup) { mHeaderView = ((ViewGroup) v).getChildAt(0); // pay attention to this if (mHeaderView == null || (!(mHeaderView instanceof LinearLayout) && !(mHeaderView instanceof RelativeLayout))) { throw new IllegalArgumentException("Pull-to-refresh header view must have " + "the following layout hierachy: LinearLayout->LinearLayout->[either a LinearLayout or RelativeLayout]"); } } else { throw new IllegalArgumentException("Pull-to-refresh header view must have " + "the following layout hierachy: LinearLayout->LinearLayout->[either a LinearLayout or RelativeLayout]"); } super.addHeaderView(v, data, isSelectable); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (mHeaderViewHeight == 0 && mHeaderView != null) { // after the first "laying-out", we get the original height of header view mHeaderViewHeight = mHeaderView.getHeight(); mHeaderViewLayoutParams = mHeaderView.getLayoutParams(); // set the header height to 0 in advance. "post(Runnable)" below is queued up // to run in the main thread, which may delay for some time mHeaderViewLayoutParams.height = 0; // hide the header view post(new Runnable() { @Override public void run() { setHeaderViewHeightInternal(0); } }); } } public void setPullToLoadMoreFooterView(View footerView) { if (!(footerView instanceof PullToLoadMoreCallback)) { throw new IllegalArgumentException("Pull-to-load-more footer view must implement PullToLoadMoreCallback"); } mSavedFooterView = (PullToLoadMoreCallback)footerView; ((View)mSavedFooterView).setVisibility(GONE); addFooterView(footerView); footerView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!mIsLoadingMore && mFooterView != null) { mIsLoadingMore = true; mFooterView.onStartLoadingMore(); if (mOnLoadMoreListener != null) { mOnLoadMoreListener.onLoadMore(); } } } }); } public void setOnRefreshListener(OnRefreshListener listener) { mOnRefreshListener = listener; } public void setOnLoadMoreListener(OnLoadMoreListener listener) { mOnLoadMoreListener = listener; } public void finishRefreshing() { if (mIsRefreshing) { mCancellingRefreshing = true; mIsRefreshing = false; if (mOrigHeaderView != null) { mOrigHeaderView.onEndRefreshing(); } mScroller.forceFinished(true); // hide the header view, with a smooth bouncing effect springBack(-mHeaderViewHeight + getScrollY()); // setSelection(0); } } public void finishLoadingMore() { if (mIsLoadingMore) { mIsLoadingMore = false; if (mFooterView != null) { mFooterView.onEndLoadingMore(); } } } public void resetLoadMoreFooterView() { if (mSavedFooterView != null) { mFooterView = mSavedFooterView; } if (mFooterView != null) { mFooterView.onReset(); } } public void enableLoadMore(boolean enable) { if (enable) { if (mSavedFooterView != null) { mFooterView = mSavedFooterView; ((View)mFooterView).setVisibility(VISIBLE); } } else if (mFooterView != null) { ((View)mFooterView).setVisibility(GONE); mSavedFooterView = mFooterView; mFooterView = null; } } public boolean isLoadingMoreEnabled() { return mFooterView != null; } protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) { if (!isTouchEvent && mScroller.isFinished() && mVelocityTracker != null) { mVelocityTracker.computeCurrentVelocity((int)(16 * mScreenDensity), mMaximumVelocity); int yVelocity = (int) mVelocityTracker.getYVelocity(0); if ((Math.abs(yVelocity) > mMinimumVelocity)) { mScroller.fling(0, getScrollY(), 0, -yVelocity, 0, 0, -mMaximumVelocity, mMaximumVelocity); postInvalidate(); } } return true; } private void initOrResetVelocityTracker() { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } else { mVelocityTracker.clear(); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // for whatever reason, stop the scroller when the user *might* // start new touch-scroll gestures. mScroller.forceFinished(true); mLastY = ev.getRawY(); mIsTouching = true; mCancellingRefreshing = false; initOrResetVelocityTracker(); mVelocityTracker.addMovement(ev); break; } return super.onInterceptTouchEvent(ev); } private VelocityTracker mVelocityTracker; @Override public boolean onTouchEvent(MotionEvent ev) { mVelocityTracker.addMovement(ev); switch (ev.getAction()) { case MotionEvent.ACTION_MOVE: float y = ev.getRawY(); int deltaY = (int)(y - mLastY); if (deltaY == 0) { return true; } if (mIsBeingTouchScrolled) { if (getChildCount() > 0) { handleTouchScroll(deltaY); } mLastY = y; } else if (Math.abs(deltaY) > mTouchSlop) { // check if the delta-y has exceeded the threshold mIsBeingTouchScrolled = true; mLastY = y; break; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mIsTouching = false; mIsBeingTouchScrolled = false; // 'getScrollY != 0' means that content of the ListView is off screen. // Or if it is not in "refreshing" state while height of the header view // is greater than 0, we must set it to 0 with a smooth bounce effect if ((getScrollY() != 0 || (!mIsRefreshing && getCurrentHeaderViewHeight() > 0))) { springBack(); // it is safe to digest the touch events here return true; } break; } int curScrollY = getScrollY(); // if not in 'refreshing' state or scrollY is less than zero, and height of // header view is greater than zero. we should keep the the first item of the // ListView always at the top(we are decreasing height of the header view, without // calling setSelection(0), we will decrease height of the header view and scroll // the ListView itself at the same time, which will cause scrolling too fast // when decreasing height of the header view) if ((!mIsRefreshing && getCurrentHeaderViewHeight() > 0) || curScrollY < 0) { // setSelection(0); return true; } else if (curScrollY > 0) { // setSelection(getCount() - 1); return true; } // let the original ListView handle the touch events return super.onTouchEvent(ev); } private void handleTouchScroll(int deltaY) { boolean reachTopEdge = reachTopEdge(); boolean reachBottomEdge = reachBottomEdge(); if (!reachTopEdge && !reachBottomEdge) { // since we are at the middle of the ListView, we don't // need to handle any touch events return; } final int scrollY = getScrollY(); int listViewHeight = getHeight(); // 0.4f is just a number that gives OK effect out of many tests. it means nothing special float scale = ((float)listViewHeight - Math.abs(scrollY) - getCurrentHeaderViewHeight()) / getHeight() * 0.4f; int newDeltaY = Math.round(deltaY * scale); if (newDeltaY != 0) { deltaY = newDeltaY; } if (reachTopEdge) { if (deltaY > 0) { scrollDown(deltaY); } else { scrollUp(deltaY); } } else { if (deltaY > 0) { if (scrollY > 0) { // when scrollY is greater than 0, it means we reach the bottom of the list // and the ListView is scrolled off the screen from the bottom, now we // scrollDown() to scroll it back, otherwise, we just let the original ListView // handle the scroll_down events scrollDown(Math.min(deltaY, scrollY)); } } else { scrollUp(deltaY); } } } private boolean reachTopEdge() { int childCount = getChildCount(); if (childCount > 0) { return (getFirstVisiblePosition() == 0) && (getChildAt(0).getTop() == 0); } else { return true; } } private boolean reachBottomEdge() { int childCount = getChildCount(); if (childCount > 0) { return (getLastVisiblePosition() == getCount() - 1) && (getChildAt(childCount - 1).getBottom() <= getHeight()); } return true; } private void springBack() { int scrollY = getScrollY(); int curHeaderViewHeight = getCurrentHeaderViewHeight(); if (curHeaderViewHeight == mHeaderViewHeight && mHeaderViewHeight > 0) { if (!mIsRefreshing && mOrigHeaderView != null) { mIsRefreshing = true; mOrigHeaderView.onStartRefreshing(); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } } else { scrollY -= curHeaderViewHeight; } if (scrollY != 0) { if (mFooterView != null && !mIsLoadingMore) { if (scrollY >= mLoadingMorePullDistanceThreshold) { mIsLoadingMore = true; mFooterView.onStartLoadingMore(); if (mOnLoadMoreListener != null) { mOnLoadMoreListener.onLoadMore(); } } else if (scrollY > 0) { mFooterView.onCancelPulling(); } } if (!mCancellingRefreshing) { springBack(scrollY); } } } public void startLoadingMoreManually() { if (!isLoadingMoreEnabled()) { enableLoadMore(true); } if (mFooterView != null) { mIsLoadingMore = true; mFooterView.onStartLoadingMore(); if (mOnLoadMoreListener != null) { mOnLoadMoreListener.onLoadMore(); } } } private void springBack(int scrollY) { mScroller.startScroll(0, scrollY, 0, -scrollY, DEFAULT_MAX_OVER_SCROLL_DURATION); postInvalidate(); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { int scrollY = getScrollY(); // if not in "refreshing" state, we must decrease height of the // header view to 0 if (!mIsRefreshing && getCurrentHeaderViewHeight() > 0) { scrollY -= getCurrentHeaderViewHeight(); } final int deltaY = mScroller.getCurrY() - scrollY; if (deltaY < 0) { scrollDown(-deltaY); } else { scrollUp(-deltaY); } if (mCancellingRefreshing && mOnRefreshListener != null && deltaY == 0) { mCancellingRefreshing = false; mOnRefreshListener.onRefreshAnimationEnd(); } postInvalidate(); } else if (!mIsTouching && (getScrollY() != 0 || (!mIsRefreshing && getCurrentHeaderViewHeight() != 0))) { springBack(); } super.computeScroll(); } /** * scrollDown() does 2 things: * * 1. check if height of the header view is greater than 0, if so, decrease it to 0 * * 2. scroll content of the ListView off the screen any there's any deltaY left(i.e. * deltaY is not 0) */ private void scrollDown(int deltaY) { if (!mIsRefreshing && getScrollY() <= 0 && reachTopEdge()) { final int curHeaderViewHeight = getCurrentHeaderViewHeight(); if (curHeaderViewHeight < mHeaderViewHeight) { int newHeaderViewHeight = curHeaderViewHeight + deltaY; if (newHeaderViewHeight < mHeaderViewHeight) { setHeaderViewHeight(newHeaderViewHeight); return ; } else { setHeaderViewHeight(mHeaderViewHeight); deltaY = newHeaderViewHeight - mHeaderViewHeight; } } } scrollBy(0, -deltaY); } /** * scrollUp() does 3 things: * * 1. if scrollY is less than 0, it means we have scrolled the list off the screen * from the top, now we scroll back and make the list to reach the top edge of * the screen. * * 2. check height of the header view and see if it is greater than 0, if so, we * decrease it and make it zero. * * 3. now check if we have scrolled the list to reach the bottom of the screen, if so * we scroll the list off the screen from the bottom. */ private void scrollUp(int deltaY) { final int scrollY = getScrollY(); if (scrollY < 0) { if (scrollY < deltaY) { // both scrollY and deltaY are less than 0 scrollBy(0, -deltaY); return; } else { scrollTo(0, 0); deltaY -= scrollY; if (deltaY == 0) { return; } } } if (!mIsRefreshing) { int curHeaderViewHeight = getCurrentHeaderViewHeight(); if (curHeaderViewHeight > 0) { int newHeaderViewHeight = curHeaderViewHeight + deltaY; if (newHeaderViewHeight > 0) { setHeaderViewHeight(newHeaderViewHeight); return; } else { setHeaderViewHeight(0); deltaY = newHeaderViewHeight; } } } if (reachBottomEdge()) { scrollBy(0, -deltaY); } } @Override public void scrollTo(int x, int y) { int oldScrollY = getScrollY(); super.scrollTo(x, y); if (mOrigHeaderView != null && y < 0 && !mIsRefreshing) { int curTotalScrollY = getCurrentHeaderViewHeight() + (-y); mOrigHeaderView.onPull(curTotalScrollY); } else if (mFooterView != null && !mIsLoadingMore) { int halfPullDistanceThreshold = mLoadingMorePullDistanceThreshold / 2; if (y > halfPullDistanceThreshold) { if (oldScrollY <= halfPullDistanceThreshold) { mFooterView.onStartPulling(); } else if (oldScrollY < mLoadingMorePullDistanceThreshold && y >= mLoadingMorePullDistanceThreshold) { mFooterView.onReachAboveRefreshThreshold(); } else if (oldScrollY >= mLoadingMorePullDistanceThreshold && y < mLoadingMorePullDistanceThreshold) { mFooterView.onReachBelowRefreshThreshold(); } } else { mFooterView.onCancelPulling(); } } } private void setHeaderViewHeight(int height) { if (mHeaderViewLayoutParams != null && (mHeaderViewLayoutParams.height != 0 || height != 0)) { setHeaderViewHeightInternal(height); } } private void setHeaderViewHeightInternal(int height) { int oldHeight = mHeaderViewLayoutParams.height; mHeaderViewLayoutParams.height = height; // if mHeaderView is visible(I mean within the confines of the visible screen), we should // request the mHeaderView to re-layout itself, if mHeaderView is not visibble, we should // redraw the ListView itself, which ensures correct scroll position of the ListView. if (mHeaderView.isShown()) { mHeaderView.requestLayout(); } else { invalidate(); } if (mOrigHeaderView != null && !mIsRefreshing && !mCancellingRefreshing) { mOrigHeaderView.onPull(height); if (oldHeight < mHeaderViewHeight && height == mHeaderViewHeight) { mOrigHeaderView.onReachAboveHeaderViewHeight(); } else if (oldHeight == mHeaderViewHeight && height < mHeaderViewHeight) { if (height != 0) { // initial setup mOrigHeaderView.onReachBelowHeaderViewHeight(); } } } } private int getCurrentHeaderViewHeight() { if (mHeaderViewLayoutParams != null) { return mHeaderViewLayoutParams.height; } return 0; } /** * The listener to be registered through OverScrollListView.setOnRefreshListener() */ public static interface OnRefreshListener { void onRefresh(); void onRefreshAnimationEnd(); } /** * The interface to be implemented by header view to be used with OverScrollListView */ public interface PullToRefreshCallback { // scrollY = how far have we pulled? void onPull(int scrollY); void onReachAboveHeaderViewHeight(); void onReachBelowHeaderViewHeight(); void onStartRefreshing(); void onEndRefreshing(); } public static interface OnLoadMoreListener { void onLoadMore(); } public interface PullToLoadMoreCallback { void onReset(); void onStartPulling(); void onReachAboveRefreshThreshold(); void onReachBelowRefreshThreshold(); void onStartLoadingMore(); void onEndLoadingMore(); void onCancelPulling(); } }
package me.nallar.patched.storage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import com.google.common.collect.ImmutableSetMultimap; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.registry.GameRegistry; import me.nallar.exception.ConcurrencyError; import me.nallar.patched.annotation.FakeExtend; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.collections.NonBlockingLongSet; import me.nallar.tickthreading.minecraft.ChunkGarbageCollector; import me.nallar.tickthreading.minecraft.TickThreading; import me.nallar.tickthreading.patcher.Declare; import me.nallar.tickthreading.util.DoNothingRunnable; import me.nallar.tickthreading.util.ServerThreadFactory; import me.nallar.tickthreading.util.concurrent.NativeMutex; import me.nallar.unsafe.UnsafeUtil; import net.minecraft.entity.EnumCreatureType; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.PlayerManager; import net.minecraft.util.IProgressUpdate; import net.minecraft.util.LongHashMap; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.EmptyChunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.gen.ChunkProviderServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager; import org.cliffc.high_scale_lib.NonBlockingHashMapLong; /** * This is a replacement for ChunkProviderServer * Instead of attempting to patch a class with many different implementations, * this replaces it with an implementation which is intended to be compatible * with both Forge and MCPC+. */ @FakeExtend public abstract class ThreadedChunkProvider extends ChunkProviderServer implements IChunkProvider { /** * You may also use a synchronized block on generateLock, * and are encouraged to unless tryLock() is required. * This works as NativeMutex uses JVM monitors internally. */ public final NativeMutex generateLock = new NativeMutex(); private static final ThreadPoolExecutor chunkLoadThreadPool; static { chunkLoadThreadPool = new ThreadPoolExecutor(1, Runtime.getRuntime().availableProcessors(), 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ServerThreadFactory("Async ChunkLoader")); chunkLoadThreadPool.allowCoreThreadTimeOut(true); } private static final Runnable doNothingRunnable = new DoNothingRunnable(); private final NonBlockingHashMapLong<AtomicInteger> chunkLoadLocks = new NonBlockingHashMapLong<AtomicInteger>(); private final LongHashMap chunks = new LongHashMap(); private final LongHashMap loadingChunks = new LongHashMap(); private final LongHashMap unloadingChunks = new LongHashMap(); private final NonBlockingLongSet unloadStage0 = new NonBlockingLongSet(); private final ConcurrentLinkedQueue<QueuedUnload> unloadStage1 = new ConcurrentLinkedQueue<QueuedUnload>(); private final IChunkProvider generator; // Mojang shouldn't use the same interface for :( private final IChunkLoader loader; private final WorldServer world; private final Chunk defaultEmptyChunk; private final ThreadLocal<Boolean> inUnload = new BooleanThreadLocal(); private final ThreadLocal<Boolean> worldGenInProgress; private boolean loadedPersistentChunks = false; private int unloadTicks = 0; private int overloadCount = 0; private int saveTicks = 0; private Chunk lastChunk; // Mojang compatiblity fields. public final IChunkProvider currentChunkProvider; public final Set<Long> chunksToUnload = unloadStage0; public final List<Chunk> loadedChunks; public final IChunkLoader currentChunkLoader; public boolean loadChunkOnProvideRequest; public ThreadedChunkProvider(WorldServer world, IChunkLoader loader, IChunkProvider generator) { super(world, loader, generator); // This call will be removed by javassist. currentChunkProvider = this.generator = generator; this.world = world; currentChunkLoader = this.loader = loader; loadedChunks = Collections.synchronizedList(new ArrayList<Chunk>()); defaultEmptyChunk = new EmptyChunk(world, 0, 0); worldGenInProgress = world.worldGenInProgress = new BooleanThreadLocal(); world.inImmediateBlockUpdate = new BooleanThreadLocal(); } @Override @Declare public List<Chunk> getLoadedChunks() { return loadedChunks; } @Override @Declare public Set<Long> getChunksToUnloadSet() { return unloadStage0; } @Override public boolean unload100OldestChunks() { return generator.unload100OldestChunks(); } @SuppressWarnings ({"ConstantConditions", "FieldRepeatedlyAccessedInMethod"}) @Override @Declare public void tick() { int ticks = world.tickCount; // Handle unload requests if (!unloadStage0.isEmpty()) { ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> persistentChunks = world.getPersistentChunks(); PlayerManager playerManager = world.getPlayerManager(); ChunkCoordIntPair chunkCoordIntPair = new ChunkCoordIntPair(0, 0); NonBlockingHashMapLong.IteratorLong i$ = unloadStage0.iteratorLong(); int done = 0; while (i$.hasNext()) { if (done++ > 100) { break; } long key = i$.nextLong(); i$.remove(); if (key == 0) { // Iterator can't remove 0 key for some reason. unloadStage0.remove(0L); } int x = (int) key; int z = (int) (key >> 32); chunkCoordIntPair.chunkXPos = x; chunkCoordIntPair.chunkZPos = z; if (persistentChunks.containsKey(chunkCoordIntPair) || unloadingChunks.containsItem(key) || playerManager.getOrCreateChunkWatcher(x, z, false) != null) { continue; } Chunk chunk = (Chunk) chunks.getValueByKey(key); if (chunk == null || chunk.unloading || !fireBukkitUnloadEvent(chunk)) { continue; } if (lastChunk == chunk) { lastChunk = null; } chunk.unloading = true; chunk.onChunkUnload(); chunk.pendingBlockUpdates = world.getPendingBlockUpdates(chunk, false); loadedChunks.remove(chunk); chunks.remove(key); synchronized (unloadingChunks) { unloadingChunks.add(key, chunk); unloadStage1.add(new QueuedUnload(key, ticks)); } } if (loader != null) { loader.chunkTick(); } } handleUnloadQueue(ticks - 3); if (this.unloadTicks++ > 1200 && world.provider.dimensionId != 0 && TickThreading.instance.allowWorldUnloading && loadedChunks.isEmpty() && ForgeChunkManager.getPersistentChunksFor(world).isEmpty() && (!TickThreading.instance.shouldLoadSpawn || !DimensionManager.shouldLoadSpawn(world.provider.dimensionId))) { DimensionManager.unloadWorld(world.provider.dimensionId); } if (ticks % TickThreading.instance.chunkGCInterval == 0) { ChunkGarbageCollector.garbageCollect(world); } if (!loadedPersistentChunks && unloadTicks >= 5) { loadedPersistentChunks = true; int loaded = 0; int possible = world.getPersistentChunks().size(); for (ChunkCoordIntPair chunkCoordIntPair : world.getPersistentChunks().keySet()) { if (getChunkAt(chunkCoordIntPair.chunkXPos, chunkCoordIntPair.chunkZPos, doNothingRunnable) == null) { loaded++; } possible++; } if (loaded > 0) { Log.info("Loaded " + loaded + '/' + possible + " persistent chunks in " + Log.name(world)); } } } private void handleUnloadQueue(long queueThreshold) { handleUnloadQueue(queueThreshold, false); } private void handleUnloadQueue(long queueThreshold, boolean full) { int done = 0; // Handle unloading stage 1 { QueuedUnload queuedUnload; while ((queuedUnload = unloadStage1.peek()) != null && queuedUnload.ticks <= queueThreshold && (full || ++done <= 200)) { long key = queuedUnload.key; synchronized (unloadingChunks) { if (!unloadStage1.remove(queuedUnload)) { continue; } } finalizeUnload(key); } } } private boolean finalizeUnload(long key) { Chunk chunk; synchronized (unloadingChunks) { chunk = (Chunk) unloadingChunks.getValueByKey(key); } if (chunk == null) { return false; } try { if (!chunk.unloading) { return false; } synchronized (chunk) { if (chunk.alreadySavedAfterUnload) { Log.severe("Chunk save may have failed for " + key + ": " + (int) key + ',' + (int) (key >> 32)); return false; } chunk.alreadySavedAfterUnload = true; boolean notInUnload = !inUnload.get(); if (notInUnload) { inUnload.set(true); } boolean notWorldGen = !worldGenInProgress.get(); if (notWorldGen) { worldGenInProgress.set(true); } safeSaveChunk(chunk); safeSaveExtraChunkData(chunk); if (notWorldGen) { worldGenInProgress.set(false); } if (notInUnload) { inUnload.set(false); } if (chunks.containsItem(key)) { Log.severe("Failed to unload chunk " + key + ", it was reloaded during unloading"); } } } finally { if (unloadingChunks.remove(key) != chunk) { Log.severe("While unloading " + chunk + " it was replaced/removed from the unloadingChunks map."); } } return true; } // Public visibility as it will be accessed from net.minecraft.whatever, not actually this class // (Inner classes are not remapped in patching) public static class QueuedUnload { public final int ticks; public final long key; public QueuedUnload(long key, int ticks) { this.key = key; this.ticks = ticks; } } @Override public boolean chunkExists(int x, int z) { long key = key(x, z); return chunks.containsItem(key) || (worldGenInProgress.get() == Boolean.TRUE && (loadingChunks.containsItem(key) || (inUnload.get() == Boolean.TRUE && unloadingChunks.containsItem(key)))); } @Override @Declare public boolean unloadChunk(int x, int z) { long hash = key(x, z); return chunks.containsItem(hash) && unloadStage0.add(hash); } @Override public void unloadChunksIfNotNearSpawn(int x, int z) { unloadChunk(x, z); } @Override public void unloadAllChunks() { if (loadedChunks.size() > world.getPersistentChunks().size()) { synchronized (loadedChunks) { for (Chunk chunk : loadedChunks) { unloadStage0.add(key(chunk.xPosition, chunk.zPosition)); } } } } @Deprecated public void unloadChunkImmediately(int x, int z, boolean save) { long key = key(x, z); finalizeUnload(key); Chunk chunk = getChunkIfExists(x, z); if (chunk == null || !fireBukkitUnloadEvent(chunk)) { return; } chunk.unloading = true; chunk.onChunkUnload(); chunk.isChunkLoaded = false; if (save || chunk.isModified) { safeSaveChunk(chunk); safeSaveExtraChunkData(chunk); } loadedChunks.remove(chunk); chunks.remove(key); } @Deprecated public Chunk regenerateChunk(int x, int z) { unloadChunkImmediately(x, z, false); return getChunkAtInternal(x, z, true, true); } @Override public final Chunk provideChunk(int x, int z) { Chunk chunk = getChunkIfExists(x, z); if (chunk != null) { return chunk; } if (loadChunkOnProvideRequest) { return getChunkAtInternal(x, z, true, false); } return defaultEmptyChunk; } @Override public final Chunk loadChunk(int x, int z) { return getChunkAt(x, z, true, false, null); } @Override @Declare public final Chunk getChunkAt(final int x, final int z, final Runnable runnable) { return getChunkAt(x, z, true, false, runnable); } @Override @Declare public final Chunk getChunkAt(final int x, final int z, boolean allowGenerate, final Runnable runnable) { return getChunkAt(x, z, allowGenerate, false, runnable); } @Override @Declare public final Chunk getChunkIfExists(int x, int z) { Chunk chunk = lastChunk; if (chunk != null && chunk.xPosition == x && chunk.zPosition == z) { return chunk; } long key = key(x, z); chunk = (Chunk) chunks.getValueByKey(key); if (chunk == null && worldGenInProgress.get() == Boolean.TRUE) { chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null && inUnload.get() == Boolean.TRUE) { chunk = (Chunk) unloadingChunks.getValueByKey(key); } } if (chunk == null) { return null; } lastChunk = chunk; return chunk; } @Override @Declare public final Chunk getChunkAt(final int x, final int z, boolean allowGenerate, boolean regenerate, final Runnable runnable) { Chunk chunk = getChunkIfExists(x, z); if (chunk != null) { if (runnable != null) { runnable.run(); } return chunk; } if (runnable != null) { chunkLoadThreadPool.execute(new ChunkLoadRunnable(x, z, allowGenerate, regenerate, runnable, this)); return null; } return getChunkAtInternal(x, z, allowGenerate, regenerate); } @SuppressWarnings ("ConstantConditions") private Chunk getChunkAtInternal(final int x, final int z, boolean allowGenerate, boolean regenerate) { if (worldGenInProgress.get() == Boolean.TRUE || Thread.holdsLock(generateLock)) { return defaultEmptyChunk; } long key = key(x, z); Chunk chunk; final AtomicInteger lock = getLock(key); boolean wasGenerated = false; try { boolean inLoadingMap = false; // Lock on the lock for this chunk - prevent multiple instances of the same chunk synchronized (lock) { chunk = (Chunk) chunks.getValueByKey(key); if (chunk != null) { return chunk; } chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null) { finalizeUnload(key); chunk = regenerate ? null : safeLoadChunk(x, z); if (chunk != null && (chunk.xPosition != x || chunk.zPosition != z)) { Log.severe("Chunk at " + chunk.xPosition + ',' + chunk.zPosition + " was stored at " + x + ',' + z + "\nResetting this chunk."); chunk = null; } if (chunk == null) { loadingChunks.add(key, defaultEmptyChunk); if (!allowGenerate || generator == null) { return defaultEmptyChunk; } } else { loadingChunks.add(key, chunk); inLoadingMap = true; } } else { inLoadingMap = true; } } // Unlock this chunk - avoids a deadlock // Thread A - requests chunk A - needs genned // Thread B - requests chunk B - needs genned // In thread A, redpower tries to load chunk B // because its marble gen is buggy. // Thread B is now waiting for the generate lock, // Thread A is waiting for the lock on chunk B // Lock the generation lock - ChunkProviderGenerate isn't threadsafe at all // TODO: Possibly make ChunkProviderGenerate threadlocal? Would need many changes to // structure code to get it to work properly. synchronized (generateLock) { synchronized (lock) { chunk = (Chunk) chunks.getValueByKey(key); if (chunk != null) { return chunk; } worldGenInProgress.set(Boolean.TRUE); try { chunk = (Chunk) loadingChunks.getValueByKey(key); if (chunk == null) { Log.severe("Failed to load chunk " + chunk + " at " + x + ',' + z + " as it is missing from the loading chunks map."); return defaultEmptyChunk; } if (chunk == defaultEmptyChunk) { try { chunk = generator.provideChunk(x, z); if (chunk == null) { Log.severe("Null chunk was generated for " + x + ',' + z + " by " + generator); return defaultEmptyChunk; } chunk.isTerrainPopulated = false; wasGenerated = true; } catch (Throwable t) { Log.severe("Failed to generate a chunk in " + Log.name(world) + " at chunk coords " + x + ',' + z); throw UnsafeUtil.throwIgnoreChecked(t); } } else { if (generator != null) { generator.recreateStructures(x, z); } } if (!inLoadingMap) { loadingChunks.add(key, chunk); } chunk.threadUnsafeChunkLoad(); chunks.add(key, chunk); loadedChunks.add(chunk); } finally { worldGenInProgress.set(Boolean.FALSE); } } chunk.populateChunk(this, this, x, z); } } finally { if (lock.decrementAndGet() == 0) { loadingChunks.remove(key); } } chunk.onChunkLoad(); fireBukkitLoadEvent(chunk, wasGenerated); chunkLoadLocks.remove(key); return chunk; } private AtomicInteger getLock(long key) { AtomicInteger lock = chunkLoadLocks.get(key); if (lock != null) { lock.incrementAndGet(); return lock; } AtomicInteger newLock = new AtomicInteger(1); lock = chunkLoadLocks.putIfAbsent(key, newLock); if (lock != null) { lock.incrementAndGet(); return lock; } return newLock; } @Override @Declare public void fireBukkitLoadEvent(Chunk chunk, boolean newlyGenerated) { } @Override @Declare public boolean fireBukkitUnloadEvent(Chunk chunk) { return true; } @Override protected Chunk safeLoadChunk(int x, int z) { if (loader == null) { return null; } try { Chunk chunk = loader.loadChunk(world, x, z); if (chunk != null) { chunk.lastSaveTime = world.getTotalWorldTime(); } return chunk; } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to load chunk at " + x + ',' + z); return null; } } @Override protected void safeSaveExtraChunkData(Chunk chunk) { if (loader == null) { return; } try { loader.saveExtraChunkData(world, chunk); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to save extra chunk data for " + chunk); } } @Override protected void safeSaveChunk(Chunk chunk) { if (loader == null) { return; } try { chunk.lastSaveTime = world.getTotalWorldTime(); loader.saveChunk(world, chunk); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Failed to save chunk " + chunk); } } @Override public void populate(IChunkProvider chunkProvider, int x, int z) { if (!Thread.holdsLock(generateLock)) { Log.severe("Attempted to populate chunk without locking generateLock", new ConcurrencyError("Caused by: incorrect external code")); } Chunk chunk = getChunkIfExists(x, z); if (chunk == null) { Log.warning("Attempted to populate chunk which is not loaded at " + x + ',' + z, new Exception()); return; } synchronized (chunk) { if (chunk.isTerrainPopulated) { Log.warning("Attempted to populate chunk " + x + ',' + z + " which is already populated."); return; } if (generator != null) { generator.populate(chunkProvider, x, z); GameRegistry.generateWorld(x, z, world, generator, chunkProvider); fireBukkitPopulateEvent(chunk); chunk.setChunkModified(); } // It may have been modified in generator.populate/GameRegistry.generateWorld. //noinspection ConstantConditions if (chunk.isTerrainPopulated) { Log.warning("Chunk " + chunk + " had its isTerrainPopulated field set to true incorrectly by external code while populating"); } chunk.isTerrainPopulated = true; } } @Override @Declare public void fireBukkitPopulateEvent(Chunk chunk) { } @Override public boolean saveChunks(boolean fullSaveRequired, IProgressUpdate progressUpdate) { boolean saveAll = fullSaveRequired || saveTicks++ % 512 == 0; int savedChunks = 0; List<Chunk> chunksToSave = new ArrayList<Chunk>(); synchronized (loadedChunks) { for (Chunk chunk : loadedChunks) { if (!chunk.unloading && chunk.needsSaving(saveAll)) { chunk.isModified = false; chunksToSave.add(chunk); } } } for (Chunk chunk : chunksToSave) { if (chunk.unloading) { continue; } if (chunks.getValueByKey(key(chunk.xPosition, chunk.zPosition)) != chunk) { if (MinecraftServer.getServer().isServerRunning()) { Log.warning("Not saving " + chunk + ", not in correct location in chunks map."); } continue; } if (fullSaveRequired) { safeSaveExtraChunkData(chunk); } safeSaveChunk(chunk); if (++savedChunks == 256 && !saveAll) { if ((++overloadCount) > 50) { Log.warning("Partial save queue overloaded in " + Log.name(world) + ". You should decrease saveInterval. Only saved " + savedChunks + " out of " + chunksToSave.size()); } return true; } } if (overloadCount > 0) { overloadCount } if (fullSaveRequired) { handleUnloadQueue(Long.MAX_VALUE, true); if (loader != null) { loader.saveExtraData(); } } return true; } @Override public boolean canSave() { return !world.canNotSave; } @Override public String makeString() { return "Loaded " + loadedChunks.size() + " Loading " + loadingChunks.getNumHashElements() + " Unload " + unloadStage0.size() + " UnloadSave " + unloadStage1.size() + " Locks " + chunkLoadLocks.size(); } @Override public List getPossibleCreatures(EnumCreatureType creatureType, int x, int y, int z) { return generator.getPossibleCreatures(creatureType, x, y, z); } @Override public ChunkPosition findClosestStructure(World world, String name, int x, int y, int z) { return generator.findClosestStructure(world, name, x, y, z); } @Override public int getLoadedChunkCount() { return loadedChunks.size(); } @Override public void recreateStructures(int x, int z) { } private static long key(int x, int z) { return (((long) z) << 32) | (x & 0xffffffffL); } public static class ChunkLoadRunnable implements Runnable { private final int x; private final int z; private final Runnable runnable; private final ChunkProviderServer provider; private final boolean allowGenerate; private final boolean regenerate; public ChunkLoadRunnable(int x, int z, boolean allowGenerate, boolean regenerate, Runnable runnable, ChunkProviderServer provider) { this.x = x; this.z = z; this.allowGenerate = allowGenerate; this.regenerate = regenerate; this.runnable = runnable; this.provider = provider; } @Override public void run() { try { Chunk chunk = provider.getChunkAt(x, z, allowGenerate, regenerate, null); if (chunk == null || (allowGenerate && chunk instanceof EmptyChunk)) { FMLLog.warning("Failed to load chunk at " + x + ',' + z + " asynchronously. Provided " + chunk); } else { runnable.run(); } } catch (Throwable t) { FMLLog.log(Level.SEVERE, t, "Exception loading chunk asynchronously."); } } } public static class BooleanThreadLocal extends ThreadLocal<Boolean> { @Override public Boolean initialValue() { return false; } } }
package org.intermine.api.profile; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.intermine.api.InterMineAPITestCase; import org.intermine.api.profile.TagManager.TagNameException; import org.intermine.api.profile.TagManager.TagNamePermissionException; import org.intermine.model.InterMineObject; import org.intermine.model.userprofile.Tag; import org.intermine.model.userprofile.UserProfile; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.objectstore.query.SingletonResults; public class TagManagerTest extends InterMineAPITestCase { private Profile bobProfile; private ProfileManager pm; private TagManager manager; public TagManagerTest(String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); pm = im.getProfileManager(); bobProfile = new Profile(pm, "bob", 101, "bob_pass", new HashMap(), new HashMap(), new HashMap(), true, false); pm.createProfile(bobProfile); manager = im.getTagManager(); } public void testDeleteTag() { manager.addTag("list1Tag", "list1", "bag", "bob"); // test that tag was added successfully assertEquals(1, manager.getTags("list1Tag", "list1", "bag", "bob").size()); manager.deleteTag("list1Tag", "list1", "bag", "bob"); // test that tag was deleted assertEquals(0, manager.getTags("list1Tag", "list1", "bag", "bob").size()); } public void testGetTags() throws Exception { manager.addTag("list1Tag", "list1", "bag", "bob"); manager.addTag("list2Tag", "list2", "bag", "bob"); manager.addTag("list3Tag", "list3", "bag", "bob"); manager.addTag("list4Tag", "list_", "bag", "bob"); List<Tag> tags = manager.getTags(null, null, null, "bob"); assertEquals(4, tags.size()); assertTrue("Tag added to database but not retrieved.", tagExists(tags, "list1Tag", "list1", "bag", "bob")); assertTrue("Tag added to database but not retrieved.", tagExists(tags, "list2Tag", "list2", "bag", "bob")); assertTrue("Tag added to database but not retrieved.", tagExists(tags, "list3Tag", "list3", "bag", "bob")); assertEquals(1, manager.getTags(null, "list_", "bag", "bob").size()); } public void testAddTag() { Tag createdTag = manager.addTag("wowTag", "list1", "bag", "bob"); Tag retrievedTag = manager.getTags("wowTag", "list1", "bag", "bob").get(0); assertEquals(createdTag, retrievedTag); assertEquals(createdTag.getTagName(), "wowTag"); assertEquals(createdTag.getObjectIdentifier(), "list1"); assertEquals(createdTag.getType(), "bag"); assertEquals(createdTag.getUserProfile().getUsername(), "bob"); } public void testAddWithProfile() throws Exception { Tag createdTag = manager.addTag("wowTag", "list1", "bag", bobProfile); Tag retrievedTag = manager.getTags("wowTag", "list1", "bag", "bob").get(0); assertEquals(createdTag, retrievedTag); assertEquals(createdTag.getTagName(), "wowTag"); assertEquals(createdTag.getObjectIdentifier(), "list1"); assertEquals(createdTag.getType(), "bag"); assertEquals(createdTag.getUserProfile().getUsername(), "bob"); } public void testAddPermissionProblems() throws Exception { try { manager.addTag("im:wowTag", "list1", "bag", bobProfile); fail("Expected exception"); } catch (TagManager.TagNamePermissionException e) { //Bob is not allowed to add im tags, because he is not the superuser } } public void testAddNameProblems() throws Exception { try { manager.addTag("An illegal tag name!", "list1", "bag", bobProfile); fail("Expected exception"); } catch (TagManager.TagNameException e) { } } public void testGetTagById() { Tag tag = manager.addTag("list1Tag", "list1", "bag", "bob"); Tag retrievedTag = manager.getTagById(tag.getId()); assertEquals(tag, retrievedTag); } // Verifies that tag name can only contain A-Z, a-z, 0-9, '_', '-', ' ', ':', '.', ',' public void testIsValidTagName() { assertTrue(TagManager.isValidTagName("validTagName_.,- :1")); assertFalse(TagManager.isValidTagName("'; drop table userprofile;")); assertFalse(TagManager.isValidTagName(null)); assertFalse(TagManager.isValidTagName("invalidTagName@")); } private boolean tagExists(List<Tag> tags, String name, String taggedObject, String type, String userName) { for (Tag tag : tags) { if (tag.getTagName().equals(name) && tag.getObjectIdentifier().equals(taggedObject) && tag.getType().equals(type) && tag.getUserProfile().getUsername().equals(userName)) { return true; } } return false; } }
package br.edu.ufcg.computacao.si1.model; import org.springframework.security.core.authority.AuthorityUtils; import java.util.Objects; import javax.persistence.*; @Entity(name = "Usuario") @Table(name = "tb_usuario") public class Usuario extends org.springframework.security.core.userdetails.User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(nullable = false, unique = true) private Long id; @Column(nullable = false) private String nome; @Column(nullable = false, unique = true) private String email; @Column(nullable = false) private String senha; @Column(nullable = false) private RazaoSocial role; @Column private double saldo; public Usuario() { super("default", "default", AuthorityUtils.createAuthorityList(RazaoSocial.USER.toString())); } public Usuario(String nome, String email, String senha, RazaoSocial role) { super(email, senha, AuthorityUtils.createAuthorityList(role.toString())); this.nome = nome; this.email = email; this.senha = senha; this.role = role; this.saldo = 0.0; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public RazaoSocial getRole() { return role; } public void setRole(RazaoSocial role) { this.role = role; } public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } @Override public boolean equals(Object obj) { if (obj.getClass() != Usuario.class) { return false; } Usuario outro = (Usuario) obj; if (!this.nome.equals(outro.nome)) { return false; } if (!this.email.equals(outro.email)) { return false; } if (!this.senha.equals(outro.senha)) { return false; } if (!this.role.equals(outro.role)) { return false; } if (this.saldo != outro.saldo) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((email == null) ? 0 : email.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + ((role == null) ? 0 : role.hashCode()); long temp; temp = Double.doubleToLongBits(saldo); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((senha == null) ? 0 : senha.hashCode()); return result; } }
package org.intermine.dataconversion; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.sql.Database; import org.intermine.sql.DatabaseFactory; import org.intermine.task.ConverterTask; import org.apache.tools.ant.BuildException; import org.apache.log4j.Logger; /** * Initiates retrieval and conversion of data from a source database * * @author Andrew Varley * @author Mark Woodbridge * @author Matthew Wakeling */ public class DBRetrieverTask extends ConverterTask { private static final Logger LOG = Logger.getLogger(DBRetrieverTask.class); protected String database; /** * Set the database name * @param database the database name */ public void setDatabase(String database) { this.database = database; } /** * Run the task * @throws BuildException if a problem occurs */ public void execute() throws BuildException { if (database == null) { throw new BuildException("database attribute is not set"); } if (model == null) { throw new BuildException("model attribute is not set"); } ObjectStoreWriter osw = null; ItemWriter writer = null; try { Database db = DatabaseFactory.getDatabase(database); Model m = Model.getInstanceByName(model); osw = ObjectStoreWriterFactory.getObjectStoreWriter(osName); writer = new ObjectStoreItemWriter(osw); DBReader reader = new ReadAheadDBReader(db, m); System.err .println("Processing data from DB " + db.getURL()); new DBConverter(m, db, reader, writer).process(); reader.close(); } catch (Exception e) { LOG.error("problem retrieving data: ", e); throw new BuildException(e); } finally { try { writer.close(); osw.close(); } catch (Exception e) { throw new BuildException(e); } } try { doSQL(osw.getObjectStore()); } catch (Exception e) { throw new BuildException(e); } } }
package ch.sportchef.business; import pl.setblack.airomem.core.SimpleController; import java.io.Serializable; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Supplier; public enum PersistenceManager { ; private static final String SPORTCHEF_DIRECTORY_NAME = ".sportchef"; //NON-NLS private static final String PREVAYLER_DIRECTORY_NAME = "prevayler"; //NON-NLS private static final Path DATA_DIRECTORY; static { DATA_DIRECTORY = Paths.get(SPORTCHEF_DIRECTORY_NAME, PREVAYLER_DIRECTORY_NAME); } public static <T extends Serializable> SimpleController<T> createSimpleController( final Class<? extends Serializable> clazz, final Supplier<T> constructor) { final String dir = DATA_DIRECTORY.resolve(clazz.getName()).toString(); return SimpleController.loadOptional(dir, constructor); } }
/** * When a Bucket is created Simperium creates a Channel to sync changes between * a Bucket and simperium.com. * * A Channel is provided with a Simperium App ID, a Bucket to operate on, a User * who owns the bucket and a Channel.Listener that receives messages from the * Channel. * * To get messages into a Channel, Channel.receiveMessage receives a Simperium * websocket API message stripped of the channel ID prefix. * * TODO: instead of notifying the bucket about each individual item, there should be * a single event for when there's a "re-index" or after performing all changes in a * change operation. * */ package com.simperium.client; import com.simperium.util.JSONDiff; import com.simperium.util.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Timer; public class Channel implements Bucket.Channel { public interface OnMessageListener { void onMessage(MessageEvent event); void onClose(Channel channel); void onOpen(Channel channel); } public static final String TAG="Simperium.Channel"; // key names for init command json object static public final String FIELD_CLIENT_ID = "clientid"; static public final String FIELD_API_VERSION = "api"; static public final String FIELD_AUTH_TOKEN = "token"; static public final String FIELD_APP_ID = "app_id"; static public final String FIELD_BUCKET_NAME = "name"; static public final String FIELD_COMMAND = "cmd"; static public final String FIELD_LIBRARY = "library"; static public final String FIELD_LIBRARY_VERSION = "version"; static public final String LIBRARY_NAME = "android"; static public final Integer LIBRARY_VERSION = 0; // commands sent over the socket public static final String COMMAND_INIT = "init"; // init:{INIT_PROPERTIES} public static final String COMMAND_AUTH = "auth"; // received after an init: auth:expired or auth:email@example.com public static final String COMMAND_INDEX = "i"; // i:1:MARK:?:LIMIT public static final String COMMAND_CHANGE = "c"; public static final String COMMAND_VERSION = "cv"; public static final String COMMAND_ENTITY = "e"; static final String RESPONSE_UNKNOWN = "?"; static final String EXPIRED_AUTH = "expired"; // after unsuccessful init: static final String EXPIRED_AUTH_INDICATOR = "{"; static final String EXPIRED_AUTH_REASON_KEY = "msg"; static final String EXPIRED_AUTH_CODE_KEY = "code"; static final int EXPIRED_AUTH_INVALID_TOKEN_CODE = 401; // Parameters for querying bucket static final Integer INDEX_PAGE_SIZE = 50; static final Integer INDEX_BATCH_SIZE = 10; static final Integer INDEX_QUEUE_SIZE = 5; // Constants for parsing command messages static final Integer MESSAGE_PARTS = 2; static final Integer COMMAND_PART = 0; static final Integer PAYLOAD_PART = 1; static final String COMMAND_FORMAT = "%s:%s"; // bucket determines which bucket we are using on this channel private Bucket bucket; // the object the receives the messages the channel emits private OnMessageListener listener; // track channel status protected boolean started = false, connected = false, startOnConnect = false, idle = true; private boolean haveIndex = false; private CommandInvoker commands = new CommandInvoker(); private String appId, sessionId; private Serializer serializer; // for sending and receiving changes final private ChangeProcessor changeProcessor; private IndexProcessor indexProcessor; public interface Serializer { // public <T extends Syncable> void save(Bucket<T> bucket, SerializedQueue<T> data); public SerializedQueue restore(Bucket bucket); public void reset(Bucket bucket); public void onQueueChange(Change change); public void onDequeueChange(Change change); public void onSendChange(Change change); public void onAcknowledgeChange(Change change); } public static class SerializedQueue { final public Map<String,Change> pending; final public List<Change> queued; public SerializedQueue(){ this(new HashMap<String, Change>(), new ArrayList<Change>()); } public SerializedQueue(Map<String,Change> pendingChanges, List<Change> queuedChanges){ this.pending = pendingChanges; this.queued = queuedChanges; } } public Channel(String appId, String sessionId, final Bucket bucket, Serializer serializer, OnMessageListener listener){ this.serializer = serializer; this.appId = appId; this.sessionId = sessionId; this.bucket = bucket; this.listener = listener; // Receive auth: command command(COMMAND_AUTH, new Command(){ public void execute(String param){ User user = getUser(); // ignore auth:expired, implement new auth:{JSON} for failures if(EXPIRED_AUTH.equals(param.trim())) return; // if it starts with { let's see if it's error JSON if (param.indexOf(EXPIRED_AUTH_INDICATOR) == 0) { try { JSONObject authResponse = new JSONObject(param); int code = authResponse.getInt(EXPIRED_AUTH_CODE_KEY); if (code == EXPIRED_AUTH_INVALID_TOKEN_CODE) { user.setStatus(User.Status.NOT_AUTHORIZED); stop(); return; } else { // TODO retry auth? Logger.log(TAG, String.format("Unable to auth: %d", code)); return; } } catch (JSONException e) { Logger.log(TAG, String.format("Unable to parse auth JSON, assume was email %s", param)); } } user.setEmail(param); user.setStatus(User.Status.AUTHORIZED); } }); // Receive i: command command(COMMAND_INDEX, new Command(){ @Override public void execute(String param){ updateIndex(param); } }); // Receive c: command command(COMMAND_CHANGE, new Command(){ @Override public void execute(String param){ handleRemoteChanges(param); } }); // Receive e: command command(COMMAND_ENTITY, new Command(){ @Override public void execute(String param){ handleVersionResponse(param); } }); changeProcessor = new ChangeProcessor(); } public String toString(){ return String.format("%s<%s>", super.toString(), bucket.getName()); } protected Ghost onAcknowledged(RemoteChange remoteChange, Change acknowledgedChange) throws RemoteChangeInvalidException { // if this isn't a removal, update the ghost for the relevant object return bucket.acknowledgeChange(remoteChange, acknowledgedChange); } protected void onError(RemoteChange remoteChange, Change erroredChange){ Logger.log(TAG, String.format("Received error from service %s", remoteChange)); } protected Ghost onRemote(RemoteChange remoteChange) throws RemoteChangeInvalidException { return bucket.applyRemoteChange(remoteChange); } @Override public void reset(){ changeProcessor.reset(); } private boolean hasChangeVersion(){ return bucket.hasChangeVersion(); } private String getChangeVersion(){ return bucket.getChangeVersion(); } private void getLatestVersions(){ // TODO: should local changes still be stored? // abort any remote and local changes since we're getting new data // and top the processor changeProcessor.abort(); haveIndex = false; // initialize the new query for new index data IndexQuery query = new IndexQuery(); // send the i:::: messages sendMessage(query.toString()); } /** * Diffs and object's local modifications and queues up the changes */ public Change queueLocalChange(Syncable object){ Change change = new Change(Change.OPERATION_MODIFY, object); changeProcessor.addChange(change); return change; } public Change queueLocalDeletion(Syncable object){ Change change = new Change(Change.OPERATION_REMOVE, object); changeProcessor.addChange(change); return change; } private static final String INDEX_CURRENT_VERSION_KEY = "current"; private static final String INDEX_VERSIONS_KEY = "index"; private static final String INDEX_MARK_KEY = "mark"; private void updateIndex(String indexJson){ // if we don't have an index processor, create a new one for the associated cv // listen for when the index processor is done so we can start the changeprocessor again // if we do have an index processor and the cv's match, add the page of items // to the queue. if (indexJson.equals(RESPONSE_UNKNOWN)) { // refresh the index getLatestVersions(); return; } JSONObject index; try { index = new JSONObject(indexJson); } catch (JSONException e) { Logger.log(TAG, String.format("Index had invalid json: %s", indexJson)); return; } // if we don't have a processor or we are getting a different cv if (indexProcessor == null || !indexProcessor.addIndexPage(index)) { // make sure we're not processing changes and clear pending changes // TODO: pause the change processor instead of clearing it :( changeProcessor.reset(); // start a new index String currentIndex; try { currentIndex = index.getString(INDEX_CURRENT_VERSION_KEY); } catch(JSONException e){ // we have an empty index currentIndex = ""; } indexProcessor = new IndexProcessor(getBucket(), currentIndex, indexProcessorListener); indexProcessor.start(index); } else { // received an index page for a different change version // TODO: reconcile the out of band index cv } } private IndexProcessorListener indexProcessorListener = new IndexProcessorListener(){ @Override public void onComplete(String cv){ haveIndex = true; } }; private void handleRemoteChanges(String changesJson){ JSONArray changes; if (changesJson.equals(RESPONSE_UNKNOWN)) { Logger.log(TAG, "CV is out of date"); changeProcessor.reset(); getLatestVersions(); return; } try { changes = new JSONArray(changesJson); } catch (JSONException e){ Logger.log(TAG, "Failed to parse remote changes JSON", e); return; } // Loop through each change? Convert changes to array list changeProcessor.addChanges(changes); } private static final String ENTITY_DATA_KEY = "data"; private void handleVersionResponse(String versionData){ // versionData will be: key.version\n{"data":ENTITY} // we need to parse out the key and version, parse the json payload and // retrieve the data if (indexProcessor == null || !indexProcessor.addObjectData(versionData)) { Logger.log(TAG, String.format("Unkown Object for index: %s", versionData)); } } public Bucket getBucket(){ return bucket; } public User getUser(){ return bucket.getUser(); } public String getSessionId(){ return sessionId; } public boolean isStarted(){ return started; } public boolean isConnected(){ return connected; } /** * ChangeProcessor has no work to do */ public boolean isIdle(){ return idle; } /** * Send Bucket's init message to start syncing changes. */ @Override public void start(){ if (started) { // we've already started return; } // If socket isn't connected yet we have to wait until connection // is up and try starting then if (!connected) { if (listener != null) listener.onOpen(this); startOnConnect = true; return; } if (!bucket.getUser().hasAccessToken()) { // we won't connect unless we have an access token return; } started = true; Object initialCommand; if (!hasChangeVersion()) { // the bucket has never gotten an index haveIndex = false; initialCommand = new IndexQuery(); } else { // retive changes since last cv haveIndex = true; initialCommand = String.format("%s:%s", COMMAND_VERSION, getChangeVersion()); } // Build the required json object for initializing HashMap<String,Object> init = new HashMap<String,Object>(6); init.put(FIELD_API_VERSION, 1); init.put(FIELD_CLIENT_ID, sessionId); init.put(FIELD_APP_ID, appId); init.put(FIELD_AUTH_TOKEN, bucket.getUser().getAccessToken()); init.put(FIELD_BUCKET_NAME, bucket.getRemoteName()); init.put(FIELD_COMMAND, initialCommand); init.put(FIELD_LIBRARY_VERSION, LIBRARY_VERSION); init.put(FIELD_LIBRARY, LIBRARY_NAME); String initParams = new JSONObject(init).toString(); String message = String.format(COMMAND_FORMAT, COMMAND_INIT, initParams); sendMessage(message); } /** * Saves syncing state and tells listener to close */ @Override public void stop(){ startOnConnect = false; started = false; changeProcessor.stop(); if (listener != null) { listener.onClose(this); } } // websocket public void onConnect(){ connected = true; Logger.log(TAG, String.format("onConnect autoStart? %b", startOnConnect)); if(startOnConnect) start(); } public void onDisconnect(){ started = false; connected = false; changeProcessor.stop(); } /** * Receive a message from the WebSocketManager which already strips the channel * prefix from the message. */ public void receiveMessage(String message){ // parse the message and react to it String[] parts = message.split(":", MESSAGE_PARTS); String command = parts[COMMAND_PART]; executeCommand(command, parts[1]); } // send without the channel id, the socket manager should know which channel is writing private void sendMessage(String message){ // send a message if (listener != null) { MessageEvent event = new MessageEvent(this, message); listener.onMessage(event); } } public static class MessageEvent extends EventObject { public String message; public MessageEvent(Channel source, String message){ super(source); this.message = message; } public String getMessage(){ return message; } public String toString(){ return getMessage(); } } private void command(String name, Command command){ commands.add(name, command); } private void executeCommand(String name, String params){ commands.executeCommand(name, params); } /** * Command and CommandInvoker provide a declaritive syntax for handling commands that come in * from Channel.onMessage. Takes a message like "auth:user@example.com" and finds the correct * command to run and stips the command from the message so the command can take care of * processing the params. * * channel.command("auth", new Command(){ * public void onRun(String params){ * // params is now either an email address or "expired" * } * }); */ private interface Command { void execute(String params); } private class CommandInvoker { private HashMap<String,Command> commands = new HashMap<String,Command>(); protected CommandInvoker add(String name, Command command){ commands.put(name, command); return this; } protected void executeCommand(String name, String params){ if (commands.containsKey(name)) { Command command = commands.get(name); command.execute(params); } else { Logger.log(TAG, String.format("Unkown command received: %s", name)); } } } static final String CURSOR_FORMAT = "%s::%s::%s"; static final String QUERY_DELIMITER = ":"; // static final Integer INDEX_MARK = 2; // static final Integer INDEX_LIMIT = 5; /** * IndexQuery provides an interface for managing a query cursor and limit fields. * TODO: add a way to build an IndexQuery from an index response */ private class IndexQuery { private String mark = ""; private Integer limit = INDEX_PAGE_SIZE; public IndexQuery(){}; public IndexQuery(String mark){ this(mark, INDEX_PAGE_SIZE); } public IndexQuery(Integer limit){ this.limit = limit; } public IndexQuery(String mark, Integer limit){ this.mark = mark; this.limit = limit; } public String toString(){ String limitString = ""; if (limit > -1) { limitString = limit.toString(); } return String.format(CURSOR_FORMAT, COMMAND_INDEX, mark, limitString); } } public static class ObjectVersion { private String key; private Integer version; public ObjectVersion(String key, Integer version){ this.key = key; this.version = version; } public String getKey(){ return key; } public Integer getVersion(){ return version; } public String toString(){ return String.format("%s.%d", key, version); } public static ObjectVersion parseString(String versionString) throws java.text.ParseException { int lastDot = versionString.lastIndexOf("."); if (lastDot == -1) { throw new java.text.ParseException(String.format("Missing version string: %s", versionString), versionString.length()); } String key = versionString.substring(0, lastDot); String version = versionString.substring(lastDot + 1); return new ObjectVersion(key, Integer.parseInt(version)); } } private interface IndexProcessorListener { void onComplete(String cv); } /** * When index data is received it should queue up entities in the IndexProcessor. * The IndexProcessor then receives the object data and on a seperate thread asks * the StorageProvider to persist the object data. The storageProvider's operation * should not block the websocket thread in any way. * * Build up a list of entities and versions we need for the index. Allow the * channel to pass in the version data */ private class IndexProcessor { public static final String INDEX_OBJECT_ID_KEY = "id"; public static final String INDEX_OBJECT_VERSION_KEY = "v"; final private String cv; final private Bucket bucket; private List<String> queue = Collections.synchronizedList(new ArrayList<String>()); private IndexQuery nextQuery; private boolean complete = false; final private IndexProcessorListener listener; int indexedCount = 0; public IndexProcessor(Bucket bucket, String cv, IndexProcessorListener listener){ this.bucket = bucket; this.cv = cv; this.listener = listener; } public Boolean addObjectData(String versionData){ String[] objectParts = versionData.split("\n"); String prefix = objectParts[0]; String payload = objectParts[1]; ObjectVersion objectVersion; try { objectVersion = ObjectVersion.parseString(prefix); } catch (java.text.ParseException e) { Logger.log(TAG, "Failed to add object data", e); return false; } if (payload.equals(RESPONSE_UNKNOWN)) { Logger.log(TAG, String.format("Object unkown to simperium: %s", objectVersion)); return false; } if (!queue.remove(objectVersion.toString())) { return false; } JSONObject data = null; try { JSONObject payloadJSON = new JSONObject(payload); data = payloadJSON.getJSONObject(ENTITY_DATA_KEY); } catch (JSONException e) { Logger.log(TAG, "Failed to parse object JSON", e); return false; } // build the ghost and update Ghost ghost = new Ghost(objectVersion.getKey(), objectVersion.getVersion(), data); bucket.addObjectWithGhost(ghost); indexedCount ++; // for every 10 items, notify progress if(indexedCount % 10 == 0) { notifyProgress(); } next(); return true; } public void start(JSONObject indexPage){ addIndexPage(indexPage); } public void next(){ // if queue isn't empty, pull it off the top and send request if (!queue.isEmpty()) { String versionString = queue.get(0); ObjectVersion version; try { version = ObjectVersion.parseString(versionString); } catch (java.text.ParseException e) { Logger.log(TAG, "Failed to parse version string, skipping", e); queue.remove(versionString); next(); return; } if (!bucket.hasKeyVersion(version.getKey(), version.getVersion())) { sendMessage(String.format("%s:%s", COMMAND_ENTITY, version.toString())); } else { Logger.log(TAG, String.format("Already have %s requesting next object", version)); queue.remove(versionString); next(); return; } return; } // if index is empty and we have a next request, make the request if (nextQuery != null){ sendMessage(nextQuery.toString()); return; } // no queue, no next query, all done! complete = true; notifyDone(); } /** * Add the page of data, but only if indexPage cv matches. Detects when it's the * last page due to absence of cursor mark */ public Boolean addIndexPage(JSONObject indexPage){ String currentIndex; try { currentIndex = indexPage.getString(INDEX_CURRENT_VERSION_KEY); } catch(JSONException e){ Logger.log(TAG, String.format("Index did not have current version %s", cv)); currentIndex = ""; } if (!currentIndex.equals(cv)) { return false; } JSONArray indexVersions; try { indexVersions = indexPage.getJSONArray(INDEX_VERSIONS_KEY); } catch(JSONException e){ Logger.log(TAG, String.format("Index did not have entities: %s", indexPage)); return true; } if (indexVersions.length() > 0) { // query for each item that we don't have locally in the bucket for (int i=0; i<indexVersions.length(); i++) { try { JSONObject version = indexVersions.getJSONObject(i); String key = version.getString(INDEX_OBJECT_ID_KEY); Integer versionNumber = version.getInt(INDEX_OBJECT_VERSION_KEY); ObjectVersion objectVersion = new ObjectVersion(key, versionNumber); queue.add(objectVersion.toString()); // if (!bucket.hasKeyVersion(key, versionNumber)) { // // we need to get the remote object // index.add(objectVersion.toString()); // // sendMessage(String.format("%s:%s.%d", COMMAND_ENTITY, key, versionNumber)); } catch (JSONException e) { Logger.log(TAG, String.format("Error processing index: %d", i), e); } } } String nextMark = null; if (indexPage.has(INDEX_MARK_KEY)) { try { nextMark = indexPage.getString(INDEX_MARK_KEY); } catch (JSONException e) { nextMark = null; } } if (nextMark != null && nextMark.length() > 0) { nextQuery = new IndexQuery(nextMark); // sendMessage(nextQuery.toString()); } else { nextQuery = null; } next(); return true; } /** * If the index is done processing */ public boolean isComplete(){ return complete; } private void notifyDone(){ bucket.indexComplete(cv); listener.onComplete(cv); } private void notifyProgress(){ bucket.notifyOnNetworkChangeListeners(Bucket.ChangeType.INDEX); } } public boolean haveCompleteIndex(){ return haveIndex; } /** * ChangeProcessor should perform operations on a seperate thread as to not block the websocket * ideally it will be a FIFO queue processor so as changes are brought in they can be appended. * We also need a way to pause and clear the queue when we download a new index. */ private class ChangeProcessor implements Runnable, Change.OnRetryListener { // public static final Integer CAPACITY = 200; public static final long RETRY_DELAY_MS = 5000; // 5 seconds for retries? private Thread thread; private List<JSONObject> remoteQueue = Collections.synchronizedList(new ArrayList<JSONObject>(10)); private List<Change> localQueue = Collections.synchronizedList(new ArrayList<Change>()); private Map<String,Change> pendingChanges = Collections.synchronizedMap(new HashMap<String,Change>()); private Timer retryTimer; private final Object lock = new Object(); public Object runLock = new Object(); public ChangeProcessor() { restore(); } /** * If thread is running */ public boolean isRunning(){ return thread != null && thread.isAlive(); } private void restore(){ synchronized(lock){ SerializedQueue serialized = serializer.restore(bucket); localQueue.addAll(serialized.queued); pendingChanges.putAll(serialized.pending); resendPendingChanges(); } } public void addChanges(JSONArray changes) { synchronized(lock){ int length = changes.length(); Logger.log(TAG, String.format("Add remote changes to processor %d", length)); for (int i = 0; i < length; i++) { JSONObject change = changes.optJSONObject(i); if (change != null) { remoteQueue.add(change); } } start(); } } public void addChange(JSONObject change) { synchronized(lock){ remoteQueue.add(change); } start(); } /** * Local change to be queued */ public void addChange(Change change){ synchronized (lock){ // compress all changes for this same key Iterator<Change> iterator = localQueue.iterator(); while(iterator.hasNext()){ Change queued = iterator.next(); if(queued.getKey().equals(change.getKey())){ serializer.onDequeueChange(queued); iterator.remove(); } } serializer.onQueueChange(change); localQueue.add(change); } start(); } public void start(){ // channel must be started and have complete index if (!started) { return; } if (retryTimer == null) { retryTimer = new Timer(); } if (thread == null || thread.getState() == Thread.State.TERMINATED) { thread = new Thread(this, String.format("simperium.processor.%s", getBucket().getName())); thread.start(); } else { // notify synchronized(runLock){ runLock.notify(); } } } public void stop(){ // interrupt the thread if (this.thread != null) { this.thread.interrupt(); synchronized(runLock){ runLock.notify(); } } } protected void reset(){ pendingChanges.clear(); serializer.reset(bucket); } protected void abort(){ reset(); stop(); } /** * Check if we have changes we can send out */ protected boolean hasQueuedChanges(){ synchronized(lock){ Logger.log(TAG, String.format("Checking for queued changes %d", localQueue.size())); // if we have have any remote changes to process we have work to do if (!remoteQueue.isEmpty()) return true; // if our local queue is empty we don't have work to do if (localQueue.isEmpty()) return false; // if we have queued changes, if there's no corresponding pending change then there's still work to do Iterator<Change> changes = localQueue.iterator(); while(changes.hasNext()){ Change change = changes.next(); if (!pendingChanges.containsKey(change.getKey())) return true; } return false; } } protected boolean hasPendingChanges(){ synchronized(lock){ return !pendingChanges.isEmpty() || !localQueue.isEmpty(); } } public void run(){ if(!haveCompleteIndex()) return; idle = false; Logger.log(TAG, String.format("%s - Starting change queue", Thread.currentThread().getName())); while(true){ try { processRemoteChanges(); processLocalChanges(); } catch (InterruptedException e) { // shut down break; } if(!hasQueuedChanges()){ // we've sent out every change that we can so far, if nothing is pending we can disconnect if (pendingChanges.isEmpty()) { idle = true; } synchronized(runLock){ try { Logger.log(TAG, String.format("Waiting <%s> idle? %b", bucket.getName(), idle)); runLock.wait(); } catch (InterruptedException e) { break; } Logger.log(TAG, "Waking change processor"); } } } retryTimer.cancel(); retryTimer = null; Logger.log(TAG, String.format("%s - Queue interrupted", Thread.currentThread().getName())); } private void processRemoteChanges() throws InterruptedException { synchronized(lock){ Logger.log(TAG, String.format("Processing remote changes %d", remoteQueue.size())); // bail if thread is interrupted while(remoteQueue.size() > 0){ if (Thread.interrupted()) { throw new InterruptedException(); } // take an item off the queue RemoteChange remoteChange = null; try { remoteChange = RemoteChange.buildFromMap(remoteQueue.remove(0)); } catch (JSONException e) { Logger.log(TAG, "Failed to build remote change", e); continue; } Boolean acknowledged = false; // synchronizing on pendingChanges since we're looking up and potentially // removing an entry Change change = null; change = pendingChanges.get(remoteChange.getKey()); if (remoteChange.isAcknowledgedBy(change)) { serializer.onAcknowledgeChange(change); // change is no longer pending so remove it pendingChanges.remove(change.getKey()); if (remoteChange.isError()) { Logger.log(TAG, String.format("Change error response! %d %s", remoteChange.getErrorCode(), remoteChange.getKey())); onError(remoteChange, change); } else { try { Ghost ghost = onAcknowledged(remoteChange, change); Change compressed = null; Iterator<Change> queuedChanges = localQueue.iterator(); while(queuedChanges.hasNext()){ Change queuedChange = queuedChanges.next(); if (queuedChange.getKey().equals(change.getKey())) { queuedChanges.remove(); if (!remoteChange.isRemoveOperation()) { compressed = queuedChange.reapplyOrigin(ghost.getVersion(), ghost.getDiffableValue()); } } } if (compressed != null) { localQueue.add(compressed); } } catch (RemoteChangeInvalidException e){ Logger.log(TAG, "Remote change could not be acknowledged", e); } } } else { if (remoteChange.isError()){ Logger.log(TAG, String.format("Remote change %s was an error but not acknowledged", remoteChange)); } else { try { onRemote(remoteChange); } catch (RemoteChangeInvalidException e) { Logger.log(TAG, "Remote change could not be applied", e); } } } if (!remoteChange.isError() && remoteChange.isRemoveOperation()) { Iterator<Change> iterator = localQueue.iterator(); while(iterator.hasNext()){ Change queuedChange = iterator.next(); if (queuedChange.getKey().equals(remoteChange.getKey())) { iterator.remove(); } } } } } } public void processLocalChanges() throws InterruptedException { synchronized(lock){ if (localQueue.isEmpty()) { return; } final List<Change> sendLater = new ArrayList<Change>(); // find the first local change whose key does not exist in the pendingChanges and there are no remote changes while(!localQueue.isEmpty()){ if (Thread.interrupted()) { localQueue.addAll(0, sendLater); throw new InterruptedException(); } // take the first change of the queue Change localChange = localQueue.remove(0); // check if there's a pending change with the same key if (pendingChanges.containsKey(localChange.getKey())) { // we have a change for this key that has not been acked // so send it later sendLater.add(localChange); // let's get the next change } else { // send the change to simperium, if the change ends up being empty // then we'll just skip it if(sendChange(localChange)) { // add the change to pending changes pendingChanges.put(localChange.getKey(), localChange); localChange.setOnRetryListener(this); // starts up the timer retryTimer.scheduleAtFixedRate(localChange.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS); } } } localQueue.addAll(0, sendLater); } } private void resendPendingChanges(){ if (retryTimer == null) { retryTimer = new Timer(); } synchronized(lock){ // resend all pending changes for (Map.Entry<String, Change> entry : pendingChanges.entrySet()) { Change change = entry.getValue(); change.setOnRetryListener(this); retryTimer.scheduleAtFixedRate(change.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS); } } } @Override public void onRetry(Change change){ sendChange(change); } private Boolean sendChange(Change change) { // send the change down the socket! if (!connected) { // channel is not initialized, send on reconnect return true; } try { JSONObject map = new JSONObject(); map.put(Change.ID_KEY, change.getKey()); map.put(Change.CHANGE_ID_KEY, change.getChangeId()); map.put(JSONDiff.DIFF_OPERATION_KEY, change.getOperation()); Integer version = change.getVersion(); if (version != null && version > 0) { map.put(Change.SOURCE_VERSION_KEY, version); } if (change.requiresDiff()) { JSONObject diff = change.getDiff(); // jsondiff.diff(change.getOrigin(), change.getTarget()); if (diff.length() == 0) { Logger.log(TAG, String.format("Discarding empty change %s diff: %s", change.getChangeId(), diff)); change.setComplete(); return false; } map.put(JSONDiff.DIFF_VALUE_KEY, diff.get(JSONDiff.DIFF_VALUE_KEY)); } // JSONObject changeJSON = Channel.serializeJSON(map); sendMessage(String.format("c:%s", map.toString())); serializer.onSendChange(change); change.setSent(); return true; } catch (JSONException e) { android.util.Log.e(TAG, "Could not send change", e); return false; } } } public static Map<String,Object> convertJSON(JSONObject json){ Map<String,Object> map = new HashMap<String,Object>(json.length()); Iterator keys = json.keys(); while(keys.hasNext()){ String key = (String)keys.next(); try { Object val = json.get(key); if (val.getClass().equals(JSONObject.class)) { map.put(key, convertJSON((JSONObject) val)); } else if (val.getClass().equals(JSONArray.class)) { map.put(key, convertJSON((JSONArray) val)); } else { map.put(key, val); } } catch (JSONException e) { Logger.log(TAG, String.format("Failed to convert JSON: %s", e.getMessage()), e); } } return map; } public static List<Object> convertJSON(JSONArray json){ List<Object> list = new ArrayList<Object>(json.length()); for (int i=0; i<json.length(); i++) { try { Object val = json.get(i); if (val.getClass().equals(JSONObject.class)) { list.add(convertJSON((JSONObject) val)); } else if (val.getClass().equals(JSONArray.class)) { list.add(convertJSON((JSONArray) val)); } else { list.add(val); } } catch (JSONException e) { Logger.log(TAG, String.format("Faile to convert JSON: %s", e.getMessage()), e); } } return list; } public static JSONObject serializeJSON(Map<String,Object>map){ JSONObject json = new JSONObject(); Iterator<String> keys = map.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object val = map.get(key); try { if (val instanceof Map) { json.put(key, serializeJSON((Map<String,Object>) val)); } else if(val instanceof List){ json.put(key, serializeJSON((List<Object>) val)); } else if(val instanceof Change){ json.put(key, serializeJSON(((Change) val).toJSONSerializable())); } else { json.put(key, val); } } catch(JSONException e){ Logger.log(TAG, String.format("Failed to serialize %s", val)); } } return json; } public static JSONArray serializeJSON(List<Object>list){ JSONArray json = new JSONArray(); Iterator<Object> vals = list.iterator(); while(vals.hasNext()){ Object val = vals.next(); if (val instanceof Map) { json.put(serializeJSON((Map<String,Object>) val)); } else if(val instanceof List) { json.put(serializeJSON((List<Object>) val)); } else if(val instanceof Change){ json.put(serializeJSON(((Change) val).toJSONSerializable())); } else { json.put(val); } } return json; } }
// Vilya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.parlor.rating.util; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import com.samskivert.util.StringUtil; import com.threerings.parlor.Log; /** * Used to keep track of the percentile distribution of positive values (generally puzzle scores). */ public class Percentiler { /** * Creates an empty percentiler. */ public Percentiler () { _total = 0; _max = 1; } /** * Creates a percentiler from its serialized representation. */ public Percentiler (byte[] data) { // decode the data ByteBuffer in = ByteBuffer.wrap(data); IntBuffer iin = in.asIntBuffer(); _max = iin.get(); iin.get(_counts); in.position((BUCKET_COUNT+1) * INT_SIZE); LongBuffer lin = in.asLongBuffer(); _snapTotal = (_total = lin.get()); // compute our percentiles recomputePercentiles(); } /** * Records a value, updating the histogram but not the percentiles (a call to {@link * #recomputePercentiles} is required for that and is sufficiently expensive that it shouldn't * be done every time a value is added). */ public void recordValue (float value) { recordValue(value, true); } /** * See {@link #recordValue(float)}. */ public void recordValue (float value, boolean logNewMax) { // if this value is larger than our maximum value, we need to redistribute our buckets if (value > _max) { // determine what our new maximum should be: twenty percent again larger than this // newly seen maximum and rounded to an integer value int newmax = (int)Math.ceil(value*1.2); float newdelta = (float)newmax / BUCKET_COUNT; if (logNewMax) { Log.info("Resizing [newmax=" + newmax + ", oldmax=" + _max + "]."); if (newmax > 2 * _max) { Log.info("Holy christ! Big newmax [value=" + value + ", oldmax=" + _max + "]."); } } // create a new counts array and map the old array to the new float delta = (float)_max / BUCKET_COUNT; int[] counts = new int[BUCKET_COUNT]; float oval = delta, nval = newdelta; for (int ii = 0, ni = 0; ii < BUCKET_COUNT; ii++, oval += delta) { // if this old bucket is entirely contained within a new bucket, add all of its // counts to the new bucket if (oval <= nval) { counts[ni] += _counts[ii]; } else { // otherwise, we need to add the appropriate fraction of this bucket's counts // to the two new buckets into which it falls float fraction = (nval - (oval - delta)) / delta; int lesser = Math.round(_counts[ii] * fraction); counts[ni] += lesser; counts[++ni] += (_counts[ii] - lesser); nval += newdelta; } } // put the remapped histogram into place _max = newmax; _counts = counts; // force a recalculation _nextRecomp = 0; } // increment the bucket associated with this value _counts[toBucketIndex(value)]++; _total++; // Log.info("Recorded [value=" + value + ", total=" + _total + "]."); // see if it's time to recompute if (_nextRecomp recomputePercentiles(); // recompute again when we've grown by 5% _nextRecomp = (int)(_total/20); } } /** * Returns the total number of values ever recorded to this percentiler. */ public long getRecordedCount () { return _total; } /** * Returns true if thsi percentiler has been modified since it was created or since the last * call to {@link #clearModified}. */ public boolean isModified () { return (_total != _snapTotal); } /** * Clears this percentiler's "is modified" state. */ public void clearModified () { _snapTotal = _total; } /** * Returns the percent of all numbers seen that are lower than the specified value. This value * can range from zero to 100 (100 in the case where this is the highest value ever seen by * this percentiler). This value reflects the percentiles computed as of the most recent call * to {@link #recomputePercentiles}. */ public int getPercentile (float value) { return _percentile[toBucketIndex(value)]; } /** * Returns the score necessary to attain the specified percentile. This value reflects the * percentiles computed as of the most recent call to {@link #recomputePercentiles}. * * @param percentile the desired percentile (from 0 to 99 inclusive). */ public float getRequiredScore (int percentile) { percentile = Math.max(0, Math.min(99, percentile)); // bound this! return _reverse[percentile] * ((float)_max / BUCKET_COUNT); } /** * Returns the largest score seen by this percentiler. */ public int getMaxScore () { return _max; } /** * Returns the scores required to obtain a percentile rating from 0 to 100. */ public float[] getRequiredScores () { float[] scores = new float[101]; for (int ii = 0; ii <= 100; ii++) { scores[ii] = getRequiredScore(ii); } return scores; } /** * Returns the counts for each bucket. */ public int[] getCounts () { return _counts.clone(); } /** * Recomputes the percentile cutoffs based on the values recorded since the last percentile * computation. */ public void recomputePercentiles () { // compute the forward mapping (score to percentile) long accum = 0; for (int ii = 0; ii < BUCKET_COUNT-1; ii++) { accum += _counts[ii]; _percentile[ii+1] = (_total == 0) ? 50 : (byte)(accum*100/_total); } // compute the reverse mapping (percentile to minimum score) for (int ii = 0, pp = 0; ii < BUCKET_COUNT; ii++) { // scan forward to the percentile bucket that maps to this percentile while (_percentile[pp] < ii && pp < (BUCKET_COUNT-1)) { pp++; } _reverse[ii] = (byte)pp; } } /** * Converts this percentiler to a byte array so that it may be stored into a database. */ public byte[] toBytes () { byte[] data = new byte[(BUCKET_COUNT+3) * INT_SIZE]; ByteBuffer out = ByteBuffer.wrap(data); IntBuffer iout = out.asIntBuffer(); iout.put(_max); iout.put(_counts); out.position((BUCKET_COUNT+1) * INT_SIZE); LongBuffer lout = out.asLongBuffer(); lout.put(_total); return data; } /** * Generates a string representation of this instance. */ public String toString () { StringBuilder buf = new StringBuilder(); buf.append("[total=").append(_total); buf.append(", max=").append(_max); buf.append(", pcts=("); for (int ii = 0; ii < 10; ii++) { if (ii > 0) { buf.append("-"); } buf.append(StringUtil.format(getRequiredScore(10*ii))); } return buf.append(")]").toString(); } /** * Dumps out our data in a format that can be used to generate a gnuplot. */ public void dumpGnuPlot (PrintStream out) { for (int ii = 0; ii < 100; ii++) { float score = (float)_max*ii/100; out.println(score + " " + _percentile[ii] + " " + _counts[ii]); } } /** * Dumps a text representation of this percentiler to the supplied print stream. */ public void dump (PrintStream out) { // obtain our maximum count int max = 0; for (int ii = 0; ii < BUCKET_COUNT; ii++) { if (_counts[ii] > max) { max = _counts[ii]; } } // figure out how many digits are needed to display the biggest bucket's size int digits = (int)Math.ceil(Math.log(max) / Math.log(10)); digits = Math.max(digits, 1); // output each bucket in a column of its own for (int rr = 9; rr >= 0; rr // print the "value" of this row out.print(StringUtil.pad("" + (rr+1)*max/10, digits) + " "); for (int ii = 0; ii < BUCKET_COUNT; ii++) { out.print((_counts[ii] * 10 / max > rr) ? "*" : " "); } out.println(""); } out.print(spaces(digits)); for (int ii = 0; ii < BUCKET_COUNT; ii++) { out.print("-"); } out.println(""); out.print(spaces(digits)); for (int ii = 0; ii < BUCKET_COUNT; ii++) { out.print(_percentile[ii]%10); } out.println(""); out.print(spaces(digits)); for (int ii = 0; ii < BUCKET_COUNT; ii++) { out.print((_percentile[ii]/10)%10); } out.println(""); // print out a scale along the very bottom out.println(""); out.println("total: " + _total + " max: " + _max + " delta: " + ((float)_max / BUCKET_COUNT)); } protected final String spaces (int count) { StringBuilder buf = new StringBuilder(); for (int ii = 0; ii < count; ii++) { buf.append(" "); } return buf.toString(); } /** * Returns the histogram bucket to which this value is assigned. */ protected final int toBucketIndex (float value) { int idx = Math.min(Math.round(value * BUCKET_COUNT / _max), 99); if (idx < 0 || idx >= BUCKET_COUNT) { Log.warning("'" + value + "' caused bogus bucket index (" + idx + ") to be computed."); Thread.dumpStack(); return 0; } return idx; } /** The total number of data points seen by this percentiler. */ protected long _total; /** The value of {@link #_total} at creation time or as of a call to {@link #clearModified}. */ protected long _snapTotal; /** The maximum value seen by this percentiler. */ protected int _max; /** Counts down to our next recalculation. */ protected int _nextRecomp; /** A histogram of all values recorded to this percentiler. */ protected int[] _counts = new int[BUCKET_COUNT]; /** The percentile associated with each bucket. */ protected byte[] _percentile = new byte[BUCKET_COUNT]; /** The bucket associated with each percentile. */ protected byte[] _reverse = new byte[BUCKET_COUNT]; /** The number of divisions between zero and our maximum value, which defines the granularity * of our histogram. */ protected static final int BUCKET_COUNT = 100; /** Number of bytes in an int; makes code clearer. */ protected static final int INT_SIZE = 4; }
package net.x4a42.volksempfaenger.ui; import net.x4a42.volksempfaenger.R; import net.x4a42.volksempfaenger.Utils; import net.x4a42.volksempfaenger.VolksempfaengerApplication; import android.content.Context; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; public class PodcastLogoView extends ImageView { private long podcastId; private VolksempfaengerApplication application; private final static DisplayImageOptions options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.default_logo) .showImageForEmptyUri(R.drawable.default_logo).cacheInMemory() .cacheOnDisc().imageScaleType(ImageScaleType.POWER_OF_2).build(); public PodcastLogoView(Context context) { super(context); init(context); } public PodcastLogoView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PodcastLogoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { application = (VolksempfaengerApplication) context .getApplicationContext(); podcastId = -1; } public void reset() { setPodcastId(-1); } public void setPodcastId(long id) { if (id != podcastId) { podcastId = id; loadImage(); } } private void loadImage() { String url = ""; if (podcastId != -1) { url = Utils.getPodcastLogoFile(getContext(), podcastId).toURI() .toString(); } application.imageLoader.displayImage(url, this, options, new SimpleImageLoadingListener() { private long startTime; @Override public void onLoadingStarted() { startTime = System.currentTimeMillis(); } @Override public void onLoadingComplete(Bitmap loadedImage) { if (System.currentTimeMillis() - startTime > 16) { Animation animation = AnimationUtils.loadAnimation( getContext(), android.R.anim.fade_in); setAnimation(animation); animation.start(); } } }); } }
package de.schenk.jrtrace.ui.util; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.runtime.Platform; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.core.ClassFile; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.texteditor.ITextEditor; public class JDTUtil { /** * Try to identify a java method based on the event:</br> * First check the current selection and see if it corresponds to a Java Method. Second check the selection in the currently * active Editor. * * @param event the event * @return an IMember if any can be identified, null if not. */ public static IMember getSelectedFunction(ExecutionEvent event) { IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); ISelection currentSelection = HandlerUtil.getCurrentSelection(event); IMember member = getSelectedFunction(currentSelection); if (member != null) return member; IEditorPart editor = page.getActiveEditor(); if(editor instanceof ITextEditor) { member=getSelectedFunction((ITextEditor)editor); } return member; } public static IMember getSelectedFunction(ITextEditor editor) { IJavaElement elem = JavaUI.getEditorInputJavaElement(editor .getEditorInput()); ITextSelection sel = (ITextSelection) editor.getSelectionProvider() .getSelection(); if (elem instanceof ClassFile) { IJavaElement selected; try { selected = ((ClassFile) elem).getElementAt(sel.getOffset()); if (selected != null && selected.getElementType() == IJavaElement.METHOD) { return (IMethod) selected; } } catch (JavaModelException e) { throw new RuntimeException(e); } } if (elem instanceof ICompilationUnit) { IJavaElement selected; try { selected = ((ICompilationUnit) elem).getElementAt(sel .getOffset()); if (selected != null && selected.getElementType() == IJavaElement.METHOD) { return (IMethod) selected; } } catch (JavaModelException e) { throw new RuntimeException(e); } } return null; } public static IMember getSelectedFunction(ISelection currentSelection) { if (currentSelection instanceof IStructuredSelection) { IStructuredSelection currentStructuredSelection = (IStructuredSelection) currentSelection; Object element = currentStructuredSelection.getFirstElement(); if (element == null) return null; if (element instanceof IMember) { return (IMember) element; } Object adapted = Platform.getAdapterManager().getAdapter(element, IMember.class); if (adapted != null) { return (IMember) element; } } return null; } }
package com.ajjpj.amapper.core.diff; import com.ajjpj.amapper.core.path.APath; /** * @author arno */ public class ADiffElement { public enum Kind { /** * Member attribute changed (to a value or null) */ Attribute, /** * TO-ONE reference changed */ RefChange, /** * TO-MANY reference element added */ Add, /** * TO-MANY reference element removed */ Remove } public final Kind kind; public final APath path; /** * marks changes that were caused by structural changes further up in the graph */ public final boolean isDerived; /** * from the <em>target</em> perspective */ public final Object oldValue; /** * from the <em>target</em> perspective */ public final Object newValue; public static ADiffElement attribute(APath path, boolean isDerived, Object oldValue, Object newValue) { return new ADiffElement(Kind.Attribute, path, isDerived, oldValue, newValue); } public static ADiffElement refChanged(APath path, boolean isDerived, Object oldValue, Object newValue) { return new ADiffElement(Kind.RefChange, path, isDerived, oldValue, newValue); } public static ADiffElement added(APath path, boolean isDerived, Object newValue) { return new ADiffElement(Kind.Add, path, isDerived, null, newValue); } public static ADiffElement removed(APath path, boolean isDerived, Object oldValue) { return new ADiffElement(Kind.Remove, path, isDerived, oldValue, null); } private ADiffElement(Kind kind, APath path, boolean isDerived, Object oldValue, Object newValue) { this.kind = kind; this.path = path; this.isDerived = isDerived; this.oldValue = oldValue; this.newValue = newValue; } @Override public String toString() { return "ADiffElement{" + "kind=" + kind + ", path=" + path + ", isDerived=" + isDerived + ", oldValue=" + oldValue + ", newValue=" + newValue + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ADiffElement that = (ADiffElement) o; if (isDerived != that.isDerived) return false; if (kind != that.kind) return false; if (newValue != null ? !newValue.equals(that.newValue) : that.newValue != null) return false; if (oldValue != null ? !oldValue.equals(that.oldValue) : that.oldValue != null) return false; if (path != null ? !path.equals(that.path) : that.path != null) return false; return true; } @Override public int hashCode() { int result = kind != null ? kind.hashCode() : 0; result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (isDerived ? 1 : 0); result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0); result = 31 * result + (newValue != null ? newValue.hashCode() : 0); return result; } }
/** * When a Bucket is created Simperium creates a Channel to sync changes between * a Bucket and simperium.com. * * A Channel is provided with a Simperium App ID, a Bucket to operate on, a User * who owns the bucket and a Channel.Listener that receives messages from the * Channel. * * To get messages into a Channel, Channel.receiveMessage receives a Simperium * websocket API message stripped of the channel ID prefix. * */ package com.simperium.client; import com.simperium.Version; import com.simperium.SimperiumException; import com.simperium.util.JSONDiff; import com.simperium.util.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.concurrent.Executor; public class Channel implements Bucket.Channel { public static class ChangeNotSentException extends ChangeException { public ChangeNotSentException(Change change, String message) { super(change, message); } public ChangeNotSentException(Change change, Throwable cause) { super(change, cause); } } public interface OnMessageListener { void onMessage(MessageEvent event); void onLog(Channel channel, int level, CharSequence message); void onClose(Channel channel); void onOpen(Channel channel); } public static final String TAG="Simperium.Channel"; // key names for init command json object static public final String FIELD_CLIENT_ID = "clientid"; static public final String FIELD_API_VERSION = "api"; static public final String FIELD_AUTH_TOKEN = "token"; static public final String FIELD_APP_ID = "app_id"; static public final String FIELD_BUCKET_NAME = "name"; static public final String FIELD_COMMAND = "cmd"; static public final String FIELD_LIBRARY = "library"; static public final String FIELD_LIBRARY_VERSION = "version"; static public final String SIMPERIUM_API_VERSION = "1.1"; static public final String LIBRARY_NAME = "android"; static public final Integer LIBRARY_VERSION = 0; // commands sent over the socket public static final String COMMAND_INIT = "init"; // init:{INIT_PROPERTIES} public static final String COMMAND_AUTH = "auth"; // received after an init: auth:expired or auth:email@example.com public static final String COMMAND_INDEX = "i"; // i:1:MARK:?:LIMIT public static final String COMMAND_CHANGE = "c"; public static final String COMMAND_VERSION = "cv"; public static final String COMMAND_ENTITY = "e"; static public final String COMMAND_INDEX_STATE = "index"; static final String RESPONSE_UNKNOWN = "?"; static final String EXPIRED_AUTH = "expired"; // after unsuccessful init: static final String EXPIRED_AUTH_INDICATOR = "{"; static final String EXPIRED_AUTH_REASON_KEY = "msg"; static final String EXPIRED_AUTH_CODE_KEY = "code"; static final int EXPIRED_AUTH_INVALID_TOKEN_CODE = 401; static public final int LOG_DEBUG = ChannelProvider.LOG_DEBUG; // Parameters for querying bucket static final Integer INDEX_PAGE_SIZE = 50; static final Integer INDEX_BATCH_SIZE = 10; static final Integer INDEX_QUEUE_SIZE = 5; // Constants for parsing command messages static final Integer MESSAGE_PARTS = 2; static final Integer COMMAND_PART = 0; static final Integer PAYLOAD_PART = 1; static final String COMMAND_FORMAT = "%s:%s"; // bucket determines which bucket we are using on this channel private Bucket bucket; // the object the receives the messages the channel emits private OnMessageListener listener; // track channel status protected boolean started = false, connected = false, startOnConnect = false, idle = true; private boolean haveIndex = false; private CommandInvoker commands = new CommandInvoker(); private String appId, sessionId; private Serializer serializer; protected Executor executor; // for sending and receiving changes final private ChangeProcessor changeProcessor; private IndexProcessor indexProcessor; public interface Serializer { // public <T extends Syncable> void save(Bucket<T> bucket, SerializedQueue<T> data); public SerializedQueue restore(Bucket bucket); public void reset(Bucket bucket); public void onQueueChange(Change change); public void onDequeueChange(Change change); public void onSendChange(Change change); public void onAcknowledgeChange(Change change); } public static class SerializedQueue { final public Map<String,Change> pending; final public List<Change> queued; public SerializedQueue(){ this(new HashMap<String, Change>(), new ArrayList<Change>()); } public SerializedQueue(Map<String,Change> pendingChanges, List<Change> queuedChanges){ this.pending = pendingChanges; this.queued = queuedChanges; } } public Channel(Executor executor, String appId, String sessionId, final Bucket bucket, Serializer serializer, OnMessageListener listener){ this.executor = executor; this.serializer = serializer; this.appId = appId; this.sessionId = sessionId; this.bucket = bucket; this.listener = listener; // Receive auth: command command(COMMAND_AUTH, new Command(){ public void execute(String param){ User user = getUser(); // ignore auth:expired, implement new auth:{JSON} for failures if(EXPIRED_AUTH.equals(param.trim())) return; // if it starts with { let's see if it's error JSON if (param.indexOf(EXPIRED_AUTH_INDICATOR) == 0) { try { JSONObject authResponse = new JSONObject(param); int code = authResponse.getInt(EXPIRED_AUTH_CODE_KEY); if (code == EXPIRED_AUTH_INVALID_TOKEN_CODE) { user.setStatus(User.Status.NOT_AUTHORIZED); stop(); return; } else { // TODO retry auth? Logger.log(TAG, String.format("Unable to auth: %d", code)); return; } } catch (JSONException e) { Logger.log(TAG, String.format("Unable to parse auth JSON, assume was email %s", param)); } } user.setEmail(param); user.setStatus(User.Status.AUTHORIZED); } }); // Receive i: command command(COMMAND_INDEX, new Command(){ @Override public void execute(String param){ updateIndex(param); } }); // Receive c: command command(COMMAND_CHANGE, new Command(){ @Override public void execute(String param){ handleRemoteChanges(param); } }); // Receive e: command command(COMMAND_ENTITY, new Command(){ @Override public void execute(String param){ handleVersionResponse(param); } }); // Receive index command command(COMMAND_INDEX_STATE, new Command() { @Override public void execute(String param){ sendIndexStatus(); } }); // Receive cv:? command command(COMMAND_VERSION, new Command() { @Override public void execute(String param) { if (param.equals(RESPONSE_UNKNOWN)) { Logger.log(TAG, "CV is out of date"); stopChangesAndRequestIndex(); } } }); changeProcessor = new ChangeProcessor(); } public String toString(){ return String.format("%s<%s>", super.toString(), bucket.getName()); } protected Ghost onAcknowledged(RemoteChange remoteChange, Change acknowledgedChange) throws RemoteChangeInvalidException { // if this isn't a removal, update the ghost for the relevant object return bucket.acknowledgeChange(remoteChange, acknowledgedChange); } protected void onError(RemoteChange remoteChange, Change erroredChange){ RemoteChange.ResponseCode errorCode = remoteChange.getResponseCode(); switch (errorCode) { case INVALID_VERSION: // Bad version, client referencing a wrong or missing sv. This is a potential data // loss scenario: server may not have enough history to resolve conflicts. Client // has two options: // - re-load the entity (via e command) then overwrite the local changes // - send a change with full object (which will overwrite remote changes, history // will still be available) referencing the current sv requeueChangeWithFullObject(erroredChange); break; case INVALID_DIFF: // Server could not apply diff, resend the change with additional parameter d that // contains the whole JSON data object. Current known scenarios where this could // happen: // - Client generated an invalid diff (some old versions of iOS library) // - Client is sending string diffs and using a different encoding than server requeueChangeWithFullObject(erroredChange); break; case UNAUTHORIZED: // Grab a new authentication token (or possible you just don't // have access to that document). // TODO: update unauthorized state for User break; case NOT_FOUND: // Client is referencing an object that does not exist on server. // If client is insistent, then changing the diff such that it is creating the // object instead should make this succeed. // TODO: Allow clients to handle NOT_FOUND break; case INVALID_ID: // If it was an invalid id, changing the id could make the call succeed. If it was a // schema violation, then correction will depend on the schema. If client cannot // tell, then do not re-send since unless something changes, 400 will be sent every // time. // TODO: Allow client implemenations to handle INVALID_ID case EXCEEDS_MAX_SIZE: // Nothing to do except reduce the size of the object // TODO: Allow client implementations to handle EXCEEDS_MAX_SIZE case DUPLICATE_CHANGE: // Duplicate change, client can safely throw away the change it is attempting to send case EMPTY_CHANGE: // Empty change, nothing was changed on the server, client can ignore (and stop // sending change). case OK: // noop break; } Logger.log(TAG, String.format("Received error from service %s", remoteChange)); } @Override public void reset(){ changeProcessor.reset(); } private boolean hasChangeVersion(){ return bucket.hasChangeVersion(); } private String getChangeVersion(){ return bucket.getChangeVersion(); } private void getLatestVersions(){ // TODO: should local changes still be stored? // abort any remote and local changes since we're getting new data // and top the processor changeProcessor.abort(); haveIndex = false; // initialize the new query for new index data IndexQuery query = new IndexQuery(); // send the i:::: messages sendMessage(query.toString()); } /** * Diffs and object's local modifications and queues up the changes */ public Change queueLocalChange(Syncable object){ Change change = new Change(Change.OPERATION_MODIFY, object); changeProcessor.addChange(change); return change; } public Change queueLocalDeletion(Syncable object){ Change change = new Change(Change.OPERATION_REMOVE, object); changeProcessor.addChange(change); return change; } protected void requeueChangeWithFullObject(Change change) { change.setSendFullObject(true); changeProcessor.addChange(change); } private static final String INDEX_CURRENT_VERSION_KEY = "current"; private static final String INDEX_VERSIONS_KEY = "index"; private static final String INDEX_MARK_KEY = "mark"; private void updateIndex(String indexJson){ // if we don't have an index processor, create a new one for the associated cv // listen for when the index processor is done so we can start the changeprocessor again // if we do have an index processor and the cv's match, add the page of items // to the queue. if (indexJson.equals(RESPONSE_UNKNOWN)) { // noop, api 1.1 should not be sending ? here return; } JSONObject index; try { index = new JSONObject(indexJson); } catch (JSONException e) { Logger.log(TAG, String.format("Index had invalid json: %s", indexJson)); return; } // if we don't have a processor or we are getting a different cv if (indexProcessor == null || !indexProcessor.addIndexPage(index)) { // make sure we're not processing changes and clear pending changes // TODO: pause the change processor instead of clearing it :( changeProcessor.reset(); // start a new index String currentIndex; try { currentIndex = index.getString(INDEX_CURRENT_VERSION_KEY); } catch(JSONException e){ // we have an empty index currentIndex = ""; } indexProcessor = new IndexProcessor(getBucket(), currentIndex, indexProcessorListener); indexProcessor.start(index); } else { // received an index page for a different change version // TODO: reconcile the out of band index cv } } private IndexProcessorListener indexProcessorListener = new IndexProcessorListener(){ @Override public void onComplete(String cv){ haveIndex = true; } }; private void handleRemoteChanges(String changesJson){ JSONArray changes; if (changesJson.equals(RESPONSE_UNKNOWN)) { // noop API 1.1 does not send "?" here return; } try { changes = new JSONArray(changesJson); } catch (JSONException e){ Logger.log(TAG, "Failed to parse remote changes JSON", e); return; } // Loop through each change? Convert changes to array list changeProcessor.addChanges(changes); } private static final String ENTITY_DATA_KEY = "data"; private void handleVersionResponse(String versionData){ try { // versionData will be: key.version\n{"data":ENTITY} ObjectVersionData objectVersion = ObjectVersionData.parseString(versionData); if (indexProcessor == null) throw new ObjectVersionUnexpectedException(objectVersion); indexProcessor.addObjectData(objectVersion); } catch (ObjectVersionUnexpectedException e) { ObjectVersionData data = e.versionData; Ghost ghost = new Ghost(data.getKey(), data.getVersion(), data.getData()); bucket.updateGhost(ghost, changeProcessor); } catch (ObjectVersionUnknownException e) { log(LOG_DEBUG, String.format(Locale.US, "Object version does not exist %s", e.version)); } catch (ObjectVersionDataInvalidException e) { log(LOG_DEBUG, String.format(Locale.US, "Object version JSON data malformed %s", e.version)); } catch (ObjectVersionParseException e) { log(LOG_DEBUG, String.format(Locale.US, "Received invalid object version: %s", e.versionString)); } } /** * Stop sending changes and download a new index */ private void stopChangesAndRequestIndex() { // get the latest index getLatestVersions(); } /** * Send index status JSON */ private void sendIndexStatus() { executor.execute(new Runnable(){ @Override public void run(){ int total = bucket.count(); JSONArray objectVersions = new JSONArray(); String idKey = "id"; String versionKey = "v"; Bucket.ObjectCursor objects = bucket.allObjects(); // collect all object keys and versions while(objects.moveToNext()) { try { JSONObject objectData = new JSONObject(); Syncable object = objects.getObject(); objectData.put(idKey, object.getSimperiumKey()); objectData.put(versionKey, object.getVersion()); objectVersions.put(objectData); } catch (JSONException e) { Logger.log(TAG, "Unable to add object version", e); } } // collect all pending change keys, ccids and source versions Collection<Change> pending = changeProcessor.pendingChanges(); JSONArray pendingData = new JSONArray(); for (Change change : pending) { try { JSONObject changeData = new JSONObject(); changeData.put("id", change.getKey()); changeData.put("sv", change.getVersion()); changeData.put("ccid", change.getChangeId()); pendingData.put(changeData); } catch (JSONException e) { Logger.log(TAG, "Unable to add change", e); } } // set up the index information JSONObject index = new JSONObject(); try { index.put("index", objectVersions); index.put("current", getChangeVersion()); index.put("pending", pendingData); } catch (JSONException e) { Logger.log(TAG, "Unable to build index response", e); } // add extra debugging info JSONObject extra = new JSONObject(); try { extra.put("bucketName", bucket.getName()); extra.put("build", Version.BUILD); extra.put("version", Version.NUMBER); extra.put("client", Version.NAME); index.put("extra", extra); } catch (JSONException e) { Logger.log(TAG, "Unable to add extra info", e); } sendMessage(String.format("%s:%s", COMMAND_INDEX_STATE, index)); } }); } public Bucket getBucket(){ return bucket; } public String getBucketName(){ if (bucket != null) { return bucket.getName(); } return ""; } public User getUser(){ return bucket.getUser(); } public String getSessionId(){ return sessionId; } public boolean isStarted(){ return started; } public boolean isConnected(){ return connected; } /** * ChangeProcessor has no work to do */ public boolean isIdle(){ return idle; } public void log(int level, CharSequence message) { if (this.listener != null) { this.listener.onLog(this, level, message); } } /** * Send Bucket's init message to start syncing changes. */ @Override public void start(){ if (started) { // we've already started return; } // If socket isn't connected yet we have to wait until connection // is up and try starting then if (!connected) { if (listener != null) listener.onOpen(this); startOnConnect = true; return; } if (!bucket.getUser().hasAccessToken()) { // we won't connect unless we have an access token return; } started = true; Object initialCommand; if (!hasChangeVersion()) { // the bucket has never gotten an index haveIndex = false; initialCommand = new IndexQuery(); } else { // retive changes since last cv haveIndex = true; initialCommand = String.format("%s:%s", COMMAND_VERSION, getChangeVersion()); } // Build the required json object for initializing HashMap<String,Object> init = new HashMap<String,Object>(6); init.put(FIELD_API_VERSION, SIMPERIUM_API_VERSION); init.put(FIELD_CLIENT_ID, sessionId); init.put(FIELD_APP_ID, appId); init.put(FIELD_AUTH_TOKEN, bucket.getUser().getAccessToken()); init.put(FIELD_BUCKET_NAME, bucket.getRemoteName()); init.put(FIELD_COMMAND, initialCommand.toString()); init.put(FIELD_LIBRARY_VERSION, LIBRARY_VERSION); init.put(FIELD_LIBRARY, LIBRARY_NAME); String initParams = new JSONObject(init).toString(); String message = String.format(COMMAND_FORMAT, COMMAND_INIT, initParams); sendMessage(message); } /** * Saves syncing state and tells listener to close */ @Override public void stop(){ startOnConnect = false; started = false; if (listener != null) { listener.onClose(this); } } // websocket public void onConnect(){ connected = true; Logger.log(TAG, String.format("onConnect autoStart? %b", startOnConnect)); if(startOnConnect) start(); } public void onDisconnect(){ started = false; connected = false; } /** * Receive a message from the WebSocketManager which already strips the channel * prefix from the message. */ public void receiveMessage(String message){ // parse the message and react to it String[] parts = message.split(":", MESSAGE_PARTS); String command = parts[COMMAND_PART]; if (parts.length == 2) { executeCommand(command, parts[1]); } else if (parts.length == 1) { executeCommand(command, ""); } } // send without the channel id, the socket manager should know which channel is writing private void sendMessage(String message){ // send a message if (listener != null) { MessageEvent event = new MessageEvent(this, message); listener.onMessage(event); } } public static class MessageEvent extends EventObject { public final String message; public final Channel channel; public MessageEvent(Channel source, String message) { super(source); this.message = message; this.channel = source; } public String getMessage() { return message; } public String toString() { return getMessage(); } public Channel getChannel() { return this.channel; } } private void command(String name, Command command){ commands.add(name, command); } private void executeCommand(String name, String params){ commands.executeCommand(name, params); } /** * Command and CommandInvoker provide a declaritive syntax for handling commands that come in * from Channel.onMessage. Takes a message like "auth:user@example.com" and finds the correct * command to run and stips the command from the message so the command can take care of * processing the params. * * channel.command("auth", new Command(){ * public void onRun(String params){ * // params is now either an email address or "expired" * } * }); */ private interface Command { void execute(String params); } private class CommandInvoker { private HashMap<String,Command> commands = new HashMap<String,Command>(); protected CommandInvoker add(String name, Command command){ commands.put(name, command); return this; } protected void executeCommand(String name, String params){ if (commands.containsKey(name)) { Command command = commands.get(name); command.execute(params); } else { Logger.log(TAG, String.format("Unkown command received: %s", name)); } } } static final String CURSOR_FORMAT = "%s::%s::%s"; static final String QUERY_DELIMITER = ":"; // static final Integer INDEX_MARK = 2; // static final Integer INDEX_LIMIT = 5; /** * IndexQuery provides an interface for managing a query cursor and limit fields. * TODO: add a way to build an IndexQuery from an index response */ private class IndexQuery { private String mark = ""; private Integer limit = INDEX_PAGE_SIZE; public IndexQuery(){} public IndexQuery(String mark){ this(mark, INDEX_PAGE_SIZE); } public IndexQuery(Integer limit){ this.limit = limit; } public IndexQuery(String mark, Integer limit){ this.mark = mark; this.limit = limit; } public String toString(){ String limitString = ""; if (limit > -1) { limitString = limit.toString(); } return String.format(CURSOR_FORMAT, COMMAND_INDEX, mark, limitString); } } public static class ObjectVersion { public final String key; public final Integer version; public ObjectVersion(String key, Integer version){ this.key = key; this.version = version; } public String getKey(){ return key; } public Integer getVersion(){ return version; } public String toString(){ return String.format(Locale.US, "%s.%d", key, version); } public static ObjectVersion parseString(String versionString) throws ObjectVersionParseException { int lastDot = versionString.lastIndexOf("."); if (lastDot == -1) { throw new ObjectVersionParseException(versionString); } String key = versionString.substring(0, lastDot); String version = versionString.substring(lastDot + 1); return new ObjectVersion(key, Integer.parseInt(version)); } } public static class ObjectVersionData { public final ObjectVersion version; public final JSONObject data; public ObjectVersionData(ObjectVersion version, JSONObject data) { this.version = version; this.data = data; } public String toString() { return this.version.toString(); } public String getKey() { return this.version.key; } public Integer getVersion() { return this.version.version; } public JSONObject getData(){ return this.data; } public static ObjectVersionData parseString(String versionString) throws ObjectVersionParseException, ObjectVersionUnknownException, ObjectVersionDataInvalidException { String[] objectParts = versionString.split("\n"); String prefix = objectParts[0]; String payload = objectParts[1]; ObjectVersion objectVersion; objectVersion = ObjectVersion.parseString(prefix); if (payload.equals(RESPONSE_UNKNOWN)) { throw new ObjectVersionUnknownException(objectVersion); } try { JSONObject data = new JSONObject(payload); return new ObjectVersionData(objectVersion, data.getJSONObject(ENTITY_DATA_KEY)); } catch (JSONException e) { throw new ObjectVersionDataInvalidException(objectVersion, e); } } } /** * Thrown when e:id.v\n? received */ public static class ObjectVersionUnknownException extends SimperiumException { public final ObjectVersion version; public ObjectVersionUnknownException(ObjectVersion version) { super(); this.version = version; } } /** * Unable to parse the object key and version number from e:key.v */ public static class ObjectVersionParseException extends SimperiumException { public final String versionString; public ObjectVersionParseException(String versionString) { super(); this.versionString = versionString; } } /** * Invalid data received for e:key.v\nJSON */ public static class ObjectVersionDataInvalidException extends SimperiumException { public final ObjectVersion version; public ObjectVersionDataInvalidException(ObjectVersion version, Throwable cause) { super(cause); this.version = version; } } public static class ObjectVersionUnexpectedException extends SimperiumException { public final ObjectVersionData versionData; public ObjectVersionUnexpectedException(ObjectVersionData versionData) { super(); this.versionData = versionData; } } private interface IndexProcessorListener { void onComplete(String cv); } /** * When index data is received it should queue up entities in the IndexProcessor. * The IndexProcessor then receives the object data and on a seperate thread asks * the StorageProvider to persist the object data. The storageProvider's operation * should not block the websocket thread in any way. * * Build up a list of entities and versions we need for the index. Allow the * channel to pass in the version data */ private class IndexProcessor { public static final String INDEX_OBJECT_ID_KEY = "id"; public static final String INDEX_OBJECT_VERSION_KEY = "v"; final private String cv; final private Bucket bucket; private List<String> queue = Collections.synchronizedList(new ArrayList<String>()); private IndexQuery nextQuery; private boolean complete = false; final private IndexProcessorListener listener; int indexedCount = 0; public IndexProcessor(Bucket bucket, String cv, IndexProcessorListener listener){ this.bucket = bucket; this.cv = cv; this.listener = listener; } /** * Receive an object's version data and store it. Send the request for the * next object. */ public void addObjectData(ObjectVersionData objectVersion) throws ObjectVersionUnexpectedException { if (!queue.remove(objectVersion.toString())) throw new ObjectVersionUnexpectedException(objectVersion); // build the ghost and update Ghost ghost = new Ghost(objectVersion.getKey(), objectVersion.getVersion(), objectVersion.getData()); bucket.addObjectWithGhost(ghost); indexedCount ++; // for every 10 items, notify progress if(indexedCount % 10 == 0) { notifyProgress(); } next(); } public void start(JSONObject indexPage){ addIndexPage(indexPage); } public void next(){ // if queue isn't empty, pull it off the top and send request if (!queue.isEmpty()) { String versionString = queue.get(0); ObjectVersion version; try { version = ObjectVersion.parseString(versionString); } catch (ObjectVersionParseException e) { Logger.log(TAG, "Failed to parse version string, skipping", e); queue.remove(versionString); next(); return; } if (!bucket.hasKeyVersion(version.getKey(), version.getVersion())) { sendMessage(String.format("%s:%s", COMMAND_ENTITY, version.toString())); } else { Logger.log(TAG, String.format("Already have %s requesting next object", version)); queue.remove(versionString); next(); return; } return; } // if index is empty and we have a next request, make the request if (nextQuery != null){ sendMessage(nextQuery.toString()); return; } // no queue, no next query, all done! complete = true; notifyDone(); } /** * Add the page of data, but only if indexPage cv matches. Detects when it's the * last page due to absence of cursor mark */ public Boolean addIndexPage(JSONObject indexPage){ String currentIndex; try { currentIndex = indexPage.getString(INDEX_CURRENT_VERSION_KEY); } catch(JSONException e){ Logger.log(TAG, String.format("Index did not have current version %s", cv)); currentIndex = ""; } if (!currentIndex.equals(cv)) { return false; } JSONArray indexVersions; try { indexVersions = indexPage.getJSONArray(INDEX_VERSIONS_KEY); } catch(JSONException e){ Logger.log(TAG, String.format("Index did not have entities: %s", indexPage)); return true; } if (indexVersions.length() > 0) { // query for each item that we don't have locally in the bucket for (int i=0; i<indexVersions.length(); i++) { try { JSONObject version = indexVersions.getJSONObject(i); String key = version.getString(INDEX_OBJECT_ID_KEY); Integer versionNumber = version.getInt(INDEX_OBJECT_VERSION_KEY); ObjectVersion objectVersion = new ObjectVersion(key, versionNumber); queue.add(objectVersion.toString()); // if (!bucket.hasKeyVersion(key, versionNumber)) { // // we need to get the remote object // index.add(objectVersion.toString()); // // sendMessage(String.format("%s:%s.%d", COMMAND_ENTITY, key, versionNumber)); } catch (JSONException e) { Logger.log(TAG, String.format("Error processing index: %d", i), e); } } } String nextMark = null; if (indexPage.has(INDEX_MARK_KEY)) { try { nextMark = indexPage.getString(INDEX_MARK_KEY); } catch (JSONException e) { nextMark = null; } } if (nextMark != null && nextMark.length() > 0) { nextQuery = new IndexQuery(nextMark); // sendMessage(nextQuery.toString()); } else { nextQuery = null; } next(); return true; } /** * If the index is done processing */ public boolean isComplete(){ return complete; } private void notifyDone(){ bucket.indexComplete(cv); listener.onComplete(cv); } private void notifyProgress(){ bucket.notifyOnNetworkChangeListeners(Bucket.ChangeType.INDEX); } } public boolean haveCompleteIndex(){ return haveIndex; } /** * ChangeProcessor should perform operations on a seperate thread as to not block the websocket * ideally it will be a FIFO queue processor so as changes are brought in they can be appended. * We also need a way to pause and clear the queue when we download a new index. */ private class ChangeProcessor implements Runnable, Change.OnRetryListener { // wait 5 seconds for retries public static final long RETRY_DELAY_MS = 5000; private List<JSONObject> remoteQueue = Collections.synchronizedList(new ArrayList<JSONObject>(10)); private List<Change> localQueue = Collections.synchronizedList(new ArrayList<Change>()); private Map<String,Change> pendingChanges = Collections.synchronizedMap(new HashMap<String,Change>()); private Timer retryTimer; private final Object lock = new Object(); public ChangeProcessor() { restore(); } public Collection<Change> pendingChanges() { return pendingChanges.values(); } private void restore(){ synchronized(lock){ SerializedQueue serialized = serializer.restore(bucket); localQueue.addAll(serialized.queued); pendingChanges.putAll(serialized.pending); resendPendingChanges(); } } public void addChanges(JSONArray changes) { synchronized(lock){ int length = changes.length(); Logger.log(TAG, String.format("Add remote changes to processor %d", length)); log(LOG_DEBUG, String.format(Locale.US, "Adding %d remote changes to queue", length)); for (int i = 0; i < length; i++) { JSONObject change = changes.optJSONObject(i); if (change != null) { remoteQueue.add(change); } } start(); } } /** * Local change to be queued */ public void addChange(Change change){ synchronized (lock){ // compress all changes for this same key log(LOG_DEBUG, String.format(Locale.US, "Adding new change to queue %s.%d %s %s", change.getKey(), change.getVersion(), change.getOperation(), change.getChangeId())); Iterator<Change> iterator = localQueue.iterator(); boolean isModify = change.isModifyOperation(); while(iterator.hasNext() && isModify){ Change queued = iterator.next(); if(queued.getKey().equals(change.getKey())){ serializer.onDequeueChange(queued); iterator.remove(); } } serializer.onQueueChange(change); localQueue.add(change); } start(); } public void start(){ if (retryTimer == null) { retryTimer = new Timer(); } // schedule a run on the executor executor.execute(this); } protected void reset(){ pendingChanges.clear(); serializer.reset(bucket); } protected void abort(){ reset(); } /** * Check if we have changes we can send out */ protected boolean hasQueuedChanges(){ synchronized(lock){ Logger.log(TAG, String.format("Checking for queued changes %d", localQueue.size())); // if we have have any remote changes to process we have work to do if (!remoteQueue.isEmpty()) return true; // if our local queue is empty we don't have work to do if (localQueue.isEmpty()) return false; // if we have queued changes, if there's no corresponding pending change then there's still work to do Iterator<Change> changes = localQueue.iterator(); while(changes.hasNext()){ Change change = changes.next(); if (!pendingChanges.containsKey(change.getKey())) return true; } return false; } } protected boolean hasPendingChanges(){ synchronized(lock){ return !pendingChanges.isEmpty() || !localQueue.isEmpty(); } } /** * Change queue processes one change per run. If it has more work to do * it schedules itself on the executor. */ public void run(){ // do no start processing changes until we have an index if(!haveCompleteIndex()) return; try { // if the channel is no longer running, or the service has // been interrupted we need to exit without working if (!started || Thread.interrupted()) throw new InterruptedException(); // we are doing work idle = false; Logger.log(TAG, String.format("%s - Starting change queue", Thread.currentThread().getName())); // if we have any remote changes queued perform a change if (!remoteQueue.isEmpty()) { processRemoteChange(); executor.execute(this); return; } // if we have items on the local queue process the change if (!localQueue.isEmpty()) { Logger.log(TAG, "Processing local changes"); if(processLocalChange()){ executor.execute(this); } return; } } catch (InterruptedException e) { Logger.log(TAG, String.format("%s (%s) - change processor interrupted", getBucketName(), Thread.currentThread().getName())); } Logger.log(TAG, "No changes left to process"); // if we got here we don't have any more work to do idle = true; } /** * Take the first remote change from the remoteQueue and process it */ private void processRemoteChange() { if (remoteQueue.isEmpty()) { return; } JSONObject remoteJSON = remoteQueue.remove(0); try { RemoteChange remoteChange = RemoteChange.buildFromMap(remoteJSON); log(LOG_DEBUG, String.format("Processing remote change with cv: %s", remoteChange.getChangeVersion())); Change change = pendingChanges.get(remoteChange.getKey()); Ghost updatedGhost = null; // one of our changes is being acknowledged if (remoteChange.isAcknowledgedBy(change)) { log(LOG_DEBUG, String.format("Found pending change for remote change <%s>: %s", remoteChange.getChangeVersion(), change.getChangeId())); serializer.onAcknowledgeChange(change); // change is no longer pending so remove it pendingChanges.remove(change.getKey()); if (remoteChange.isError()) { Logger.log(TAG, String.format("Change error response! %d %s", remoteChange.getErrorCode(), remoteChange.getKey())); onError(remoteChange, change); } else { try { updatedGhost = onAcknowledged(remoteChange, change); } catch (RemoteChangeInvalidException e){ updatedGhost = null; Logger.log(TAG, "Remote change could not be acknowledged", e); log(LOG_DEBUG, String.format("Failed to acknowledge change <%s> Reason: %s", remoteChange.getChangeVersion(), e.getMessage())); } } } else { if (remoteChange.isError()){ Logger.log(TAG, String.format("Remote change %s was an error but not acknowledged", remoteChange)); log(LOG_DEBUG, String.format("Received error response for change but not waiting for any ccids <%s>", remoteChange.getChangeVersion())); } else { try { updatedGhost = bucket.applyRemoteChange(remoteChange); Logger.log(TAG, String.format("Succesfully applied remote change <%s>", remoteChange.getChangeVersion())); } catch (RemoteChangeInvalidException e) { updatedGhost = null; Logger.log(TAG, "Remote change could not be applied", e); log(LOG_DEBUG, String.format("Failed to apply change <%s> Reason: %s", remoteChange.getChangeVersion(), e.getMessage())); // request the entire object ObjectVersion version = new ObjectVersion(remoteChange.getKey(), remoteChange.getObjectVersion()); sendMessage(String.format("%s:%s", COMMAND_ENTITY, version)); } } } if (remoteChange.isError()){ return; } Change compressed = null; Iterator<Change> iterator = localQueue.iterator(); while(iterator.hasNext()) { Change queuedChange = iterator.next(); if (queuedChange.getKey().equals(remoteChange.getKey())) { serializer.onDequeueChange(queuedChange); iterator.remove(); if (!remoteChange.isRemoveOperation() && updatedGhost != null) { compressed = queuedChange.reapplyOrigin(updatedGhost.getVersion(), updatedGhost.getDiffableValue()); } } } if (compressed != null) { addChange(compressed); } } catch (JSONException e) { Logger.log(TAG, "Failed to build remote change", e); } } /** * Sends out local changes for objects that have no pending changes. Returns true if there are still local changes send. */ public boolean processLocalChange() { Logger.log(TAG, String.format("Checking local queue for changes: %d", localQueue.size())); if (localQueue.isEmpty()) { return false; } Change localChange = null; for (Change change : localQueue){ // find a local change that has no corresponding pending change if (!pendingChanges.containsKey(change.getKey())) { localChange = change; localQueue.remove(localChange); break; } } // didn't find any changes to send if (localChange == null) { Logger.log(TAG, String.format("All local changes waiting for acks")); return false; } try { pendingChanges.put(localChange.getKey(), localChange); sendChange(localChange); localChange.setOnRetryListener(this); localChange.resetTimer(); retryTimer.scheduleAtFixedRate(localChange.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS); } catch (ChangeNotSentException e) { pendingChanges.remove(localChange.getKey()); } return true; } private void resendPendingChanges(){ if (retryTimer == null) { retryTimer = new Timer(); } synchronized(lock){ // resend all pending changes for (Map.Entry<String, Change> entry : pendingChanges.entrySet()) { Change change = entry.getValue(); change.setOnRetryListener(this); retryTimer.scheduleAtFixedRate(change.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS); } } } @Override public void onRetry(Change change){ log(LOG_DEBUG, String.format("Retrying change %s", change.getChangeId())); try { sendChange(change); } catch (ChangeNotSentException e) { // do nothing the timer will trigger another send } } private void sendChange(Change change) throws ChangeNotSentException { // send the change down the socket! if (!connected) { // channel is not initialized, send on reconnect return; } try { log(LOG_DEBUG, String.format("Sending change for id: %s op: %s ccid: %s", change.getKey(), change.getOperation(), change.getChangeId())); sendMessage(String.format("c:%s", change.toJSONObject())); serializer.onSendChange(change); change.setSent(); } catch (ChangeEmptyException e) { change.setComplete(); change.resetTimer(); serializer.onDequeueChange(change); } catch (ChangeException e) { android.util.Log.e(TAG, "Could not send change", e); throw new ChangeNotSentException(change, e); } } } public static Map<String,Object> convertJSON(JSONObject json){ Map<String,Object> map = new HashMap<String,Object>(json.length()); Iterator keys = json.keys(); while(keys.hasNext()){ String key = (String)keys.next(); try { Object val = json.get(key); if (val.getClass().equals(JSONObject.class)) { map.put(key, convertJSON((JSONObject) val)); } else if (val.getClass().equals(JSONArray.class)) { map.put(key, convertJSON((JSONArray) val)); } else { map.put(key, val); } } catch (JSONException e) { Logger.log(TAG, String.format("Failed to convert JSON: %s", e.getMessage()), e); } } return map; } public static List<Object> convertJSON(JSONArray json){ List<Object> list = new ArrayList<Object>(json.length()); for (int i=0; i<json.length(); i++) { try { Object val = json.get(i); if (val.getClass().equals(JSONObject.class)) { list.add(convertJSON((JSONObject) val)); } else if (val.getClass().equals(JSONArray.class)) { list.add(convertJSON((JSONArray) val)); } else { list.add(val); } } catch (JSONException e) { Logger.log(TAG, String.format("Failed to convert JSON: %s", e.getMessage()), e); } } return list; } public static JSONObject serializeJSON(Map<String,Object>map){ JSONObject json = new JSONObject(); Iterator<String> keys = map.keySet().iterator(); while(keys.hasNext()){ String key = keys.next(); Object val = map.get(key); try { if (val instanceof Map) { json.put(key, serializeJSON((Map<String,Object>) val)); } else if(val instanceof List){ json.put(key, serializeJSON((List<Object>) val)); } else if(val instanceof Change){ json.put(key, serializeJSON(((Change) val).toJSONSerializable())); } else { json.put(key, val); } } catch(JSONException e){ Logger.log(TAG, String.format("Failed to serialize %s", val)); } } return json; } public static JSONArray serializeJSON(List<Object>list){ JSONArray json = new JSONArray(); Iterator<Object> vals = list.iterator(); while(vals.hasNext()){ Object val = vals.next(); if (val instanceof Map) { json.put(serializeJSON((Map<String,Object>) val)); } else if(val instanceof List) { json.put(serializeJSON((List<Object>) val)); } else if(val instanceof Change){ json.put(serializeJSON(((Change) val).toJSONSerializable())); } else { json.put(val); } } return json; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.server; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.samskivert.util.Invoker; import com.samskivert.util.RunQueue; import com.samskivert.util.SystemInfo; import com.threerings.presents.annotation.AuthInvoker; import com.threerings.presents.annotation.EventQueue; import com.threerings.presents.annotation.MainInvoker; import com.threerings.presents.client.Client; import com.threerings.presents.dobj.AccessController; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.RootDObjectManager; import com.threerings.presents.server.net.ConnectionManager; import static com.threerings.presents.Log.log; /** * The presents server provides a central point of access to the various facilities that make up * the presents framework. To facilitate extension and customization, a single instance of the * presents server should be created and initialized in a process. To facilitate easy access to the * services provided by the presents server, static references to the various managers are made * available in the <code>PresentsServer</code> class. These will be configured when the singleton * instance is initialized. */ @Singleton public class PresentsServer { /** Configures dependencies needed by the Presents services. */ public static class Module extends AbstractModule { @Override protected void configure () { bindInvokers(); bind(RunQueue.class).annotatedWith(EventQueue.class).to(PresentsDObjectMgr.class); bind(DObjectManager.class).to(PresentsDObjectMgr.class); bind(RootDObjectManager.class).to(PresentsDObjectMgr.class); } /** * Binds just the invokers so this can be overridden if desired. */ protected void bindInvokers() { bind(Invoker.class).annotatedWith(MainInvoker.class).to(PresentsInvoker.class); bind(Invoker.class).annotatedWith(AuthInvoker.class).to(PresentsAuthInvoker.class); } } /** * The default entry point for the server. */ public static void main (String[] args) { Injector injector = Guice.createInjector(new Module()); PresentsServer server = injector.getInstance(PresentsServer.class); try { // initialize the server server.init(injector); // check to see if we should load and invoke a test module before running the server String testmod = System.getProperty("test_module"); if (testmod != null) { try { log.info("Invoking test module [mod=" + testmod + "]."); Class<?> tmclass = Class.forName(testmod); Runnable trun = (Runnable)tmclass.newInstance(); trun.run(); } catch (Exception e) { log.warning("Unable to invoke test module '" + testmod + "'.", e); } } // start the server to running (this method call won't return until the server is shut // down) server.run(); } catch (Exception e) { log.warning("Unable to initialize server.", e); System.exit(-1); } } /** Legacy static reference to the main distributed object manager. Don't use this. If you're * writing a game, use {@link #_omgr}. */ @Deprecated public static PresentsDObjectMgr omgr; /** Legacy static reference to the invocation manager. Don't use this. If you're * writing a game, use {@link #_invmgr}. */ @Deprecated public static InvocationManager invmgr; /** * Initializes all of the server services and prepares for operation. */ public void init (Injector injector) throws Exception { // output general system information SystemInfo si = new SystemInfo(); log.info("Starting up server [os=" + si.osToString() + ", jvm=" + si.jvmToString() + ", mem=" + si.memoryToString() + "]."); // register SIGTERM, SIGINT (ctrl-c) and a SIGHUP handlers boolean registered = false; try { registered = injector.getInstance(SunSignalHandler.class).init(); } catch (Throwable t) { log.warning("Unable to register Sun signal handlers [error=" + t + "]."); } if (!registered) { injector.getInstance(NativeSignalHandler.class).init(); } // initialize our deprecated legacy static references omgr = _omgr; invmgr = _invmgr; // configure the dobject manager with our access controller _omgr.setDefaultAccessController(createDefaultObjectAccessController()); // start the main and auth invoker threads _invoker.start(); _authInvoker.start(); // provide our client manager with the injector it needs _clmgr.setInjector(injector); // configure our connection manager _conmgr.init(getListenPorts(), getDatagramPorts()); // initialize the time base services TimeBaseProvider.init(_invmgr, _omgr); } /** * Starts up all of the server services and enters the main server event loop. */ public void run () { // post a unit that will start up the connection manager when everything else in the // dobjmgr queue is processed _omgr.postRunnable(new Runnable() { public void run () { // start up the connection manager _conmgr.start(); } }); // invoke the dobjmgr event loop _omgr.run(); } /** * Defines the default object access policy for all {@link DObject} instances. The default * default policy is to allow all subscribers but reject all modifications by the client. */ protected AccessController createDefaultObjectAccessController () { return PresentsObjectAccess.DEFAULT; } /** * Returns the port on which the connection manager will listen for client connections. */ protected int[] getListenPorts () { return Client.DEFAULT_SERVER_PORTS; } /** * Returns the ports on which the connection manager will listen for datagrams. */ protected int[] getDatagramPorts () { return Client.DEFAULT_DATAGRAM_PORTS; } /** * Called once the invoker and distributed object manager have both completed processing all * remaining events and are fully shutdown. <em>Note:</em> this is called as the last act of * the invoker <em>on the invoker thread</em>. In theory no other (important) threads are * running, so thread safety should not be an issue, but be careful! */ protected void invokerDidShutdown () { } /** The manager of distributed objects. */ @Inject protected PresentsDObjectMgr _omgr; /** The manager of network connections. */ @Inject protected ConnectionManager _conmgr; /** The manager of clients. */ @Inject protected ClientManager _clmgr; /** The manager of invocation services. */ @Inject protected InvocationManager _invmgr; /** Handles orderly shutdown of our managers, etc. */ @Inject protected ShutdownManager _shutmgr; /** Handles generation of state of the server reports. */ @Inject protected ReportManager _repmgr; /** Used to invoke background tasks that should not be allowed to tie up the distributed object * manager thread (generally talking to databases and other relatively slow entities). */ @Inject @MainInvoker protected Invoker _invoker; /** Used to invoke authentication tasks. */ @Inject @AuthInvoker protected Invoker _authInvoker; }
package nitezh.ministock.domain; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Set; import nitezh.ministock.Cache; import nitezh.ministock.PreferenceCache; import nitezh.ministock.PreferenceTools; import nitezh.ministock.UserData; import nitezh.ministock.dataaccess.FxChangeRepository; import nitezh.ministock.dataaccess.GoogleStockQuoteRepository; import nitezh.ministock.dataaccess.YahooStockQuoteRepository; public class StockQuoteRepository { public static final List<String> GOOGLE_SYMBOLS = Arrays.asList(".DJI", ".IXIC"); private static String mTimeStamp; private static HashMap<String, StockQuote> mCachedQuotes; private final YahooStockQuoteRepository yahooRepository; private final GoogleStockQuoteRepository googleRepository; public StockQuoteRepository() { this.yahooRepository = new YahooStockQuoteRepository(new FxChangeRepository()); this.googleRepository = new GoogleStockQuoteRepository(); } public HashMap<String, StockQuote> getLiveQuotes(Cache cache, List<String> symbols) { HashMap<String, StockQuote> allQuotes = new HashMap<>(); List<String> yahooSymbols = new ArrayList<>(symbols); List<String> googleSymbols = new ArrayList<>(symbols); yahooSymbols.removeAll(GOOGLE_SYMBOLS); googleSymbols.retainAll(GOOGLE_SYMBOLS); HashMap<String, StockQuote> yahooQuotes = this.yahooRepository.getQuotes(cache, yahooSymbols); HashMap<String, StockQuote> googleQuotes = this.googleRepository.getQuotes(cache, googleSymbols); if (yahooQuotes != null) allQuotes.putAll(yahooQuotes); if (googleQuotes != null) allQuotes.putAll(googleQuotes); return allQuotes; } public HashMap<String, StockQuote> getQuotes( Context context, String[] symbols, boolean noCache) { HashMap<String, StockQuote> quotes = new HashMap<>(); // If fresh data is request, retrieve from the stock data provider if (noCache) { // Retrieve all widget symbols and additionally add ^DJI Set<String> widgetSymbols = UserData.getWidgetsStockSymbols(context); widgetSymbols.add("^DJI"); widgetSymbols.addAll(UserData.getPortfolioStockMap(context).keySet()); // Retrieve the data from the stock data provider quotes = getLiveQuotes( new PreferenceCache(context), Arrays.asList(widgetSymbols.toArray(new String[widgetSymbols.size()]))); } // If there is no information used the last retrieved info if (quotes.isEmpty()) { quotes = loadQuotes(context); } // Otherwise save the info else { SimpleDateFormat format = new SimpleDateFormat("dd MMM HH:mm"); String timeStamp = format.format(new Date()).toUpperCase(); saveQuotes(context, quotes, timeStamp); } // Returns only quotes requested quotes.keySet().retainAll(Arrays.asList(symbols)); return quotes; } private HashMap<String, StockQuote> loadQuotes(Context context) { // If we have cached data on the class use that for efficiency if (mCachedQuotes != null) { return mCachedQuotes; } // Create empty HashMap to store the results HashMap<String, StockQuote> quotes = new HashMap<>(); // Load the saved quotes SharedPreferences preferences = PreferenceTools.getAppPreferences(context); String savedQuotes = preferences.getString("savedQuotes", ""); String timeStamp = preferences.getString("savedQuotesTime", ""); // Parse the string and convert to a hash map if (!savedQuotes.equals("")) { try { for (String line : savedQuotes.split("\n")) { String[] values = line.split(";"); quotes.put(values[0], new StockQuote( values[0], values[1], values[2], values[3], values[4], values[5], values[6])); } } catch (Exception e) { // Don't do anything if the stored data is dodgy quotes = new HashMap<>(); } } // Update the class cache and quotes timestamp mCachedQuotes = quotes; mTimeStamp = timeStamp; return quotes; } public String getTimeStamp() { return mTimeStamp; } private void saveQuotes(Context context, HashMap<String, StockQuote> quotes, String timeStamp) { // Convert the quotes into a string and save in share preferences StringBuilder savedQuotes = new StringBuilder(); for (String symbol : quotes.keySet()) { // Ensures we do not add a line break to the last line if (!savedQuotes.toString().equals("")) { savedQuotes.append("\n"); } savedQuotes.append(quotes.get(symbol).serialize()); } // Update the class cache and quotes timestamp mCachedQuotes = quotes; mTimeStamp = timeStamp; // Save preferences Editor editor = PreferenceTools.getAppPreferences(context).edit(); editor.putString("savedQuotes", savedQuotes.toString()); editor.putString("savedQuotesTime", timeStamp); editor.apply(); } public enum StockField { PRICE, CHANGE, PERCENT, EXCHANGE, VOLUME, NAME } }
package omnikryptec.gameobject.gameobject; import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.joml.Vector3f; import omnikryptec.gameobject.component.Component; import omnikryptec.renderer.RenderChunk; import omnikryptec.test.saving.DataMap; import omnikryptec.test.saving.DataMapSerializable; import omnikryptec.util.Instance; import omnikryptec.util.SerializationUtil; import omnikryptec.util.logger.Logger; import omnikryptec.util.logger.LogLevel; /** * * @author pcfreak9000 &amp; Panzer1119 * */ public class GameObject implements DataMapSerializable, Positionable { public static enum UpdateType { DYNAMIC, STATIC; } private static class Sorter implements Comparator<Component> { @Override public int compare(Component o1, Component o2) { return ((o1.getLevel() < o2.getLevel()) ? -1 : (o1.getLevel() > o2.getLevel() ? 1 : 0)); } } private static final Sorter SORTER = new Sorter(); public static final ArrayList<GameObject> gameObjects = new ArrayList<>(); private String name; private boolean isglobal = false; private Vector3f pos = new Vector3f(); private GameObject parent = null; private boolean active = true; private Vector3f rotation = new Vector3f(); // @JsonView(GameObject.class) //To hide this while saving it private RenderChunk myChunk; private List<Component> componentsPreLogic = null; private List<Component> componentsPostLogic = null; private final Instant ULTIMATE_IDENTIFIER = Instant.now(); private UpdateType uptype = UpdateType.DYNAMIC; public GameObject setUpdateType(UpdateType t) { uptype = t; return this; } public UpdateType getUpdateType() { return uptype; } public GameObject() { this(""); } /** * creates a gameobject with no parent */ public GameObject(String name) { this(name, null); } /** * creates a gameobject with a parent. e. g. used to bind a gun to the * player * * @param parent the parent or null for no parent */ public GameObject(String name, GameObject parent) { this.name = name; this.parent = parent; if (name != null && !name.isEmpty()) { gameObjects.add(this); } } /** * if no parent is set this is the absolute position else its the postion * relative to the parent * * @param x * @param y * @param z */ public final GameObject setRelativePos(float x, float y, float z) { this.pos.x = x; this.pos.y = y; this.pos.z = z; return this; } /** * the relative xpostion if this gameobject has a parent else the absolute * xposition * * @return the relative position */ public final Vector3f getRelativePos() { return pos; } public final GameObject increaseRelativePos(float x, float y, float z) { pos.x += x; pos.y += y; pos.z += z; return this; } public final GameObject increaseRelativeRot(float x, float y, float z) { rotation.x += x; rotation.y += y; rotation.z += z; return this; } /** * the absolute xposition is always absolute * * @return the absolute xposition */ public final Vector3f getAbsolutePos() { if (parent == null) { return new Vector3f(pos); } return parent.getAbsolutePos().add(pos, new Vector3f()); } /** * the parent or null for no parent of this gameobject * * @return the parent */ public final GameObject getParent() { return parent; } /** * sets the parent for this gameobject * * @param go the parent */ public final GameObject setParent(GameObject go) { this.parent = go; return this; } public final GameObject doLogic0() { if (componentsPreLogic != null) { for (Component c : componentsPreLogic) { c.execute(this); } } update(); if (componentsPostLogic != null) { for (Component c : componentsPostLogic) { c.execute(this); } } if (getUpdateType() == UpdateType.DYNAMIC && !(this instanceof Camera)&&Instance.getGameSettings().usesRenderChunking()) { checkChunkPos(); } return this; } public final GameObject addComponent(Component c) { if (c.getLevel() < 0) { if (componentsPreLogic == null) { componentsPreLogic = new ArrayList<>(); } componentsPreLogic.add(c); componentsPreLogic.sort(SORTER); } else { if (componentsPostLogic == null) { componentsPostLogic = new ArrayList<>(); } componentsPostLogic.add(c); componentsPostLogic.sort(SORTER); } return this; } public final GameObject removeComponent(Component c) { if (c.getLevel() < 0) { if (componentsPreLogic != null) { componentsPreLogic.remove(c); if (componentsPreLogic.isEmpty()) { componentsPreLogic = null; } } } else if (componentsPostLogic != null) { componentsPostLogic.remove(c); if (componentsPostLogic.isEmpty()) { componentsPostLogic = null; } } return this; } private List<Component> tmp; public final Component[] getComponents() { if (componentsPreLogic == null && componentsPostLogic == null) { return new Component[]{}; } if (tmp == null) { tmp = new ArrayList<>(); } if (componentsPreLogic != null) { tmp.addAll(componentsPreLogic); } if (componentsPostLogic != null) { tmp.addAll(componentsPostLogic); } return tmp.toArray(new Component[1]); } @SuppressWarnings("unchecked") public final <T> T getComponent(Class<T> type) { if (componentsPreLogic != null) { for (Component c : componentsPreLogic) { if (c.getClass() == type) { return (T) c; } } } if (componentsPostLogic != null) { for (Component c : componentsPostLogic) { if (c.getClass() == type) { return (T) c; } } } return null; } @SuppressWarnings("unchecked") public final <T> ArrayList<T> getComponents(Class<T> type) { final ArrayList<T> cp = new ArrayList<>(); if (componentsPreLogic != null) { for (Component c : componentsPreLogic) { if (c.getClass() == type) { cp.add((T) c); } } } if (componentsPostLogic != null) { for (Component c : componentsPostLogic) { if (c.getClass() == type) { cp.add((T) c); } } } return cp; } /** * override this to let your gameobject do its logic then its in sight of * the cam */ protected void update() { } public final GameObject deleteOperation() { if (componentsPreLogic != null) { for (Component c : componentsPreLogic) { c.onDelete(this); } } if (componentsPostLogic != null) { for (Component c : componentsPostLogic) { c.onDelete(this); } } delete(); gameObjects.remove(this); return this; } /** * override this to let your gameobject do its things when deleted the cam */ protected void delete() { } protected final GameObject checkChunkPos() { RenderChunk oldchunk = getMyChunk(); if (oldchunk != null) { if (oldchunk.getChunkX() != getChunkX() || oldchunk.getChunkY() != getChunkY() || oldchunk.getChunkZ() != getChunkZ()) { oldchunk.getScene().addGameObject(this); oldchunk.removeGameObject(this, false); } } else if (Logger.isDebugMode()) { Logger.log("MyChunk is null (Should not happen -.-)", LogLevel.WARNING); } return this; } /** * * @return true if a parent is set */ public final boolean hasParent() { return parent != null; } /** * the chunkx. used for rendering * * @return chunkx */ public final long getChunkX() { return (long) Math.floor(getAbsolutePos().x / RenderChunk.getWidth()); } /** * the chunky. used for rendering * * @return chunky */ public final long getChunkY() { return (long) Math.floor(getAbsolutePos().y / RenderChunk.getHeight()); } public final long getChunkZ() { return (long) Math.floor(getAbsolutePos().z / RenderChunk.getDepth()); } /** * if true the gameobject is active and will be processed. * * @param b */ public final GameObject setActive(boolean b) { this.active = b; return this; } /** * is this gameobject active and should be processed? * * @return */ public final boolean isActive() { return active; } /** * sets the rotation of this gameobject in radians * * @param vec */ public final GameObject setRotation(Vector3f vec) { this.rotation = vec; return this; } /** * the relative rotation in radians of this object or if this gameobject has * no parent, the absolute rotation * * @return */ public final Vector3f getRelativeRotation() { return rotation; } /** * the absolute rotation of this GameObject in radians * * @return */ public final Vector3f getAbsoluteRotation() { if (parent == null) { return new Vector3f(rotation); } return parent.getAbsoluteRotation().add(rotation, new Vector3f()); } /** * wont copy physics! * * @param toCopy * @return */ public static GameObject copy(GameObject toCopy) { GameObject go = new GameObject(toCopy.name); go.active = toCopy.active; go.parent = toCopy.parent; go.rotation = new Vector3f(toCopy.rotation); go.pos = new Vector3f(toCopy.pos); return go; } /** * wont copy physics! * * @param toCopy */ public final GameObject setValuesFrom(GameObject toCopy) { if (toCopy == null) { return this; } name = toCopy.name; active = toCopy.active; parent = toCopy.parent; rotation = new Vector3f(toCopy.rotation); pos = new Vector3f(toCopy.pos); return this; } public final GameObject setMyChunk(RenderChunk myChunk) { this.myChunk = myChunk; return this; } public final RenderChunk getMyChunk() { return myChunk; } public final Vector3f getPos() { return pos; } public final Vector3f getRotation() { return rotation; } public final GameObject setPos(Vector3f pos) { this.pos = pos; return this; } public GameObject setGlobal(boolean b) { this.isglobal = b; return this; } public boolean isGlobal() { return isglobal; } @Override public String toString() { return String.format("%s (%d): [Position: %s, Rotation: %s]", getClass().getSimpleName(), ULTIMATE_IDENTIFIER.toEpochMilli(), pos, rotation); } public GameObject setName(String name) { this.name = name; return this; } public static final <T> T byName(Class<? extends T> c, String name, boolean onlySame) { for (GameObject gameObject : gameObjects) { if ((!onlySame && c.isAssignableFrom(gameObject.getClass()) || (onlySame && gameObject.getClass() == c)) && (gameObject.getName() == null ? name == null : gameObject.getName().equals(name))) { return (T) gameObject; } } return null; } public static final <T> T byName(Class<? extends T> c, String name) { return byName(c, name, true); } @Override public String getName() { return name; } @Override public DataMap toDataMap(DataMap data) { data.put("name", name); data.put("isglobal", isglobal); data.put("active", active); if (parent != null) { data.put("parent", parent.toDataMap(new DataMap("parent"))); } data.put("position", SerializationUtil.vector3fToString(pos)); data.put("rotation", SerializationUtil.vector3fToString(rotation)); return data; } public static GameObject newInstanceFromDataMap(DataMap data) { if (data == null) { return null; } String name = data.getString("name"); if (name == null || name.isEmpty()) { return null; } final GameObject gameObject = byName(GameObject.class, name, false); return (gameObject != null ? gameObject : new GameObject()).fromDataMap(data); } @Override public GameObject fromDataMap(DataMap data) { if (data == null) { return null; } setName(data.getString("name")); setGlobal(data.getBoolean("isglobal")); setActive(data.getBoolean("isActive")); DataMap dataMap_temp = data.getDataMap("parent"); if (parent == null) { Object parent_ = newInstanceFromDataMap(dataMap_temp); setParent((parent_ != null ? (GameObject) parent_ : null)); } else { parent.fromDataMap(dataMap_temp); // FIXME Hmmm ist die Frage weil // die Parents und id und so } setPos(SerializationUtil.stringToVector3f(data.getString("position"))); setRotation(SerializationUtil.stringToVector3f(data.getString("rotation"))); return this; } }
package com.crowdin.cli.properties; import com.crowdin.cli.utils.MessageSource; import com.crowdin.cli.utils.Utils; import com.crowdin.cli.utils.console.ConsoleUtils; import java.nio.file.Paths; import java.util.*; import static com.crowdin.cli.utils.MessageSource.Messages; public class CliProperties { private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE; public static final String PROJECT_ID = "project_id"; private static final String PROJECT_ID_ENV = "project_id_env"; public static final String API_TOKEN = "api_token"; private static final String API_TOKEN_ENV = "api_token_env"; private static final String LOGIN = "login"; private static final String LOGIN_ENV = "login_env"; public static final String BASE_PATH = "base_path"; private static final String BASE_PATH_ENV = "base_path_env"; public static final String BASE_URL = "base_url"; private static final String BASE_URL_ENV = "base_url_env"; private static final String PRESERVE_HIERARCHY = "preserve_hierarchy"; private static final String FILES = "files"; private static final String SOURCE = "source"; private static final String IGNORE = "ignore"; private static final String DEST = "dest"; private static final String TYPE = "type"; private static final String TRANSLATION = "translation"; private static final String UPDATE_OPTION = "update_option"; private static final String LANGUAGES_MAPPING = "languages_mapping"; private static final String FIRST_LINE_CONTAINS_HEADER = "first_line_contains_header"; private static final String TRANSLATE_ATTRIBUTES = "translate_attributes"; private static final String TRANSLATE_CONTENT = "translate_content"; private static final String TRANSLATABLE_ELEMENTS = "translatable_elements"; private static final String CONTENT_SEGMENTATION = "content_segmentation"; private static final String ESCAPE_QUOTES = "escape_quotes"; private static final String MULTILINGUAL_SPREADSHEET = "multilingual_spreadsheet"; private static final String SCHEME = "scheme"; private static final String TRANSLATION_REPLACE = "translation_replace"; public PropertiesBean loadProperties(HashMap<String, Object> properties) { if (properties == null) { throw new NullPointerException("CliProperties.loadProperties has null args"); } if (properties.isEmpty()) { throw new RuntimeException(RESOURCE_BUNDLE.getString("error_empty_properties_file")); } PropertiesBean pb = new PropertiesBean(); for (Map.Entry<String, Object> property : properties.entrySet()) { if (property != null && property.getKey() != null) { switch (property.getKey()) { case API_TOKEN_ENV: pb.setApiToken(Utils.getEnvironmentVariable(property.getValue().toString())); break; case BASE_PATH_ENV: pb.setBasePath(Utils.getEnvironmentVariable(property.getValue().toString())); break; case BASE_URL_ENV: pb.setBaseUrl(Utils.getEnvironmentVariable(property.getValue().toString())); break; case PROJECT_ID_ENV: pb.setProjectId(Utils.getEnvironmentVariable(property.getValue().toString())); break; default: break; } } } for (Map.Entry<String, Object> property : properties.entrySet()) { if (property != null && property.getKey() != null) { switch (property.getKey()) { case API_TOKEN: if (property.getValue() != null && !property.getValue().toString().isEmpty()) { pb.setApiToken(property.getValue().toString()); } break; case BASE_PATH: if (property.getValue() != null && !property.getValue().toString().isEmpty()) { pb.setBasePath(property.getValue().toString()); } break; case BASE_URL: if (property.getValue() != null && !property.getValue().toString().isEmpty()) { pb.setBaseUrl(property.getValue().toString()); } break; case PROJECT_ID: if (property.getValue() != null && !property.getValue().toString().isEmpty()) { pb.setProjectId(property.getValue().toString()); } break; case PRESERVE_HIERARCHY: pb.setPreserveHierarchy(Boolean.parseBoolean(property.getValue().toString())); break; case FILES: ArrayList files = (ArrayList) property.getValue(); for (Object file : files) { FileBean fileBean = new FileBean(); HashMap<String, Object> fileObj = (HashMap<String, Object>) file; for (Map.Entry<String, Object> entry : fileObj.entrySet()) { String fileObjKey = entry.getKey(); Object fileObjVal = entry.getValue(); switch (fileObjKey) { case SOURCE: fileBean.setSource(fileObjVal.toString()); break; case IGNORE: fileBean.setIgnore((List<String>) fileObjVal); break; case DEST: fileBean.setDest(fileObjVal.toString()); break; case TYPE: fileBean.setType(fileObjVal.toString()); break; case TRANSLATION: fileBean.setTranslation(fileObjVal.toString()); break; case UPDATE_OPTION: fileBean.setUpdateOption(fileObjVal.toString()); break; case LANGUAGES_MAPPING: HashMap<String, HashMap<String, String>> languagesMapping = new HashMap<>(); languagesMapping = (HashMap<String, HashMap<String, String>>) fileObjVal; fileBean.setLanguagesMapping(languagesMapping); break; case FIRST_LINE_CONTAINS_HEADER: if ("1".equals(fileObjVal.toString())) { fileBean.setFirstLineContainsHeader(Boolean.TRUE); } else if ("0".equals(fileObjVal.toString())) { fileBean.setFirstLineContainsHeader(Boolean.FALSE); } else { fileBean.setFirstLineContainsHeader(Boolean.valueOf(fileObjVal.toString())); } break; case TRANSLATE_ATTRIBUTES: if ("1".equals(fileObjVal.toString())) { fileBean.setTranslateAttributes(Boolean.TRUE); } else if ("0".equals(fileObjVal.toString())) { fileBean.setTranslateAttributes(Boolean.FALSE); } else { fileBean.setTranslateAttributes(Boolean.valueOf(fileObjVal.toString())); } break; case TRANSLATE_CONTENT: if ("1".equals(fileObjVal.toString())) { fileBean.setTranslateContent(Boolean.TRUE); } else if ("0".equals(fileObjVal.toString())) { fileBean.setTranslateContent(Boolean.FALSE); } else { fileBean.setTranslateContent(Boolean.valueOf(fileObjVal.toString())); } break; case TRANSLATABLE_ELEMENTS: fileBean.setTranslatableElements((List<String>) fileObjVal); break; case CONTENT_SEGMENTATION: if ("1".equals(fileObjVal.toString())) { fileBean.setContentSegmentation(Boolean.TRUE); } else if ("0".equals(fileObjVal.toString())) { fileBean.setContentSegmentation(Boolean.FALSE); } else { fileBean.setContentSegmentation(Boolean.valueOf(fileObjVal.toString())); } break; case ESCAPE_QUOTES: fileBean.setEscapeQuotes(Short.valueOf(fileObjVal.toString())); break; case MULTILINGUAL_SPREADSHEET: if ("1".equals(fileObjVal.toString())) { fileBean.setMultilingualSpreadsheet(Boolean.TRUE); } else if ("0".equals(fileObjVal.toString())) { fileBean.setMultilingualSpreadsheet(Boolean.FALSE); } else { fileBean.setMultilingualSpreadsheet(Boolean.valueOf(fileObjVal.toString())); } break; case SCHEME: fileBean.setScheme(fileObjVal.toString()); break; case TRANSLATION_REPLACE: HashMap<String, String> translationReplace; translationReplace = (HashMap<String, String>) fileObjVal; fileBean.setTranslationReplace(translationReplace); break; } } pb.setFiles(fileBean); } break; default: break; } } } return pb; } //todo set default values public PropertiesBean validateProperties(PropertiesBean pb) { //Property bean if (pb == null) { throw new RuntimeException( RESOURCE_BUNDLE.getString("configuration_file_is_invalid") .concat("\n\t- ") .concat(RESOURCE_BUNDLE.getString("error_property_bean_null"))); } //Preserve hierarchy if (pb.getPreserveHierarchy() == null) { pb.setPreserveHierarchy(Boolean.FALSE); } if (pb.getBasePath() != null && !pb.getBasePath().isEmpty()) { if (!Paths.get(pb.getBasePath()).isAbsolute()) { throw new RuntimeException( RESOURCE_BUNDLE.getString("configuration_file_is_invalid") .concat("\n\t- ") .concat(RESOURCE_BUNDLE.getString("bad_base_path"))); } } else { pb.setBasePath(""); } //Files List<String> messages = new ArrayList<>(); if (pb.getFiles() == null) { messages.add(RESOURCE_BUNDLE.getString("error_empty_section_files")); } else { for (FileBean file : pb.getFiles()) { //Sources if (file.getSource() == null || file.getSource().isEmpty()) { messages.add(RESOURCE_BUNDLE.getString("error_empty_source_section")); } if (Utils.isWindows() && file.getSource() != null && file.getSource().contains("/")) { file.setSource(file.getSource().replaceAll("/+", Utils.PATH_SEPARATOR_REGEX)); } if (!Utils.isWindows() && file.getSource() != null && file.getSource().contains("\\")) { file.setSource(file.getSource().replaceAll("\\\\", Utils.PATH_SEPARATOR_REGEX)); } //Translation if (file.getTranslation() == null || file.getTranslation().isEmpty()) { messages.add(RESOURCE_BUNDLE.getString("error_empty_translation_section")); } if (file.getTranslation() != null && file.getTranslation().contains("**") && file.getSource() != null && !file.getSource().contains("**")) { messages.add("error: Translation pattern " + file.getTranslation() + " is not valid. The mask `**` can't be used."); messages.add("When using `**` in 'translation' pattern it will always contain sub-path from 'source' for certain file."); } if (file.getTranslation() != null && !file.getTranslation().startsWith(Utils.PATH_SEPARATOR)) { if (file.getTranslation().contains("%language%") || file.getTranslation().contains("%locale_with_underscore%") || file.getTranslation().contains("%android_code%") || file.getTranslation().contains("%osx_code%") || file.getTranslation().contains("%two_letters_code%") || file.getTranslation().contains("%three_letters_code%") || file.getTranslation().contains("%locale%")) { String translation = Utils.PATH_SEPARATOR + file.getTranslation(); translation = translation.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); file.setTranslation(translation); } } if (Utils.isWindows() && file.getTranslation() != null && file.getTranslation().contains("/")) { file.setTranslation(file.getTranslation().replaceAll("/+", Utils.PATH_SEPARATOR_REGEX)); } if (!Utils.isWindows() && file.getTranslation() != null && file.getTranslation().contains("\\")) { file.setTranslation(file.getTranslation().replaceAll("\\\\", Utils.PATH_SEPARATOR_REGEX)); } //Ignore if (file.getIgnore() == null || file.getIgnore().isEmpty()) { } else { List<String> ignores = new ArrayList<>(); for (String ignore : file.getIgnore()) { if (Utils.isWindows() && ignore.contains("/")) { ignores.add(ignore.replaceAll("/+", Utils.PATH_SEPARATOR_REGEX)); } else if (!Utils.isWindows() && ignore.contains("\\")) { ignores.add(ignore.replaceAll("\\\\", Utils.PATH_SEPARATOR_REGEX)); } else { ignores.add(ignore); } } file.setIgnore(ignores); } //dest if (file.getDest() == null || file.getDest().isEmpty()) { } else { if (Utils.isWindows() && file.getDest() != null && file.getDest().contains("/")) { file.setDest(file.getDest().replaceAll("/+", Utils.PATH_SEPARATOR_REGEX)); } if (!Utils.isWindows() && file.getDest() != null && file.getDest().contains("\\")) { file.setDest(file.getDest().replaceAll("\\\\", Utils.PATH_SEPARATOR_REGEX)); } } //Type if (file.getType() == null || file.getType().isEmpty()) { } else { } //Update option if (file.getUpdateOption() == null || file.getUpdateOption().isEmpty()) { } else { if (!"update_as_unapproved".equals(file.getUpdateOption()) && !"update_without_changes".equals(file.getUpdateOption())) { messages.add("Parameter 'update_option' in configuration file has unacceptable value"); } } //Translate attributes if (file.getTranslateAttributes() == null) { } else { } //Translate content if (file.getTranslateContent() == null) { file.setTranslateContent(Boolean.TRUE); } else { } //Translatable elements if (file.getTranslatableElements() == null || file.getTranslatableElements().isEmpty()) { } else { } //Content segmentation if (file.getContentSegmentation() == null) { file.setContentSegmentation(Boolean.TRUE); } else { } //escape quotes if (file.getEscapeQuotes() != null && (file.getEscapeQuotes() < 0 || file.getEscapeQuotes() > 3)) { file.setEscapeQuotes((short) 3); } else { } //Language mapping if (file.getLanguagesMapping() == null || file.getLanguagesMapping().isEmpty()) { } else { } //Multilingual spreadsheet if (file.getMultilingualSpreadsheet() == null) { } //first line contain header if (file.getFirstLineContainsHeader() == null) { } else { } //scheme if (file.getScheme() == null || file.getScheme().isEmpty()) { } else { } //translation repalce if (file.getTranslationReplace() == null || file.getTranslationReplace().isEmpty()) { } else { } } if (!messages.isEmpty()) { String messagesInOne = String.join("\n\t- ", messages.toArray(new String[0])); throw new RuntimeException(RESOURCE_BUNDLE.getString("configuration_file_is_invalid")+"\n\t- "+messagesInOne); } } return pb; } private void printConfigurationFileErrorsAndExit(List<String> errors) { System.out.println(Messages.CONFIGURATION_FILE_IS_INVALID.getString()); errors.forEach(System.out::println); ConsoleUtils.exitError(); } }
package net.sf.picard.illumina; import net.sf.picard.PicardException; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.cmdline.Usage; import net.sf.picard.illumina.parser.*; import net.sf.picard.io.IoUtil; import net.sf.picard.util.*; import net.sf.picard.util.IlluminaUtil.IlluminaAdapterPair; import net.sf.samtools.*; import net.sf.samtools.util.Iso8601Date; import net.sf.samtools.util.PeekIterator; import net.sf.samtools.util.SortingCollection; import net.sf.samtools.util.StringUtil; import java.io.File; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * IlluminaBasecallsToSam transforms a lane of Illumina data file formats (bcl, locs, clocs, qseqs, etc.) into * SAM or BAM file format. * <p/> * In this application, barcode data is read from Illumina data file groups, each of which is associated with a tile. * Each tile may contain data for any number of barcodes, and a single barcode's data may span multiple tiles. Once the * barcode data is collected from files, each barcode's data is written to its own SAM/BAM. The barcode data must be * written in order; this means that barcode data from each tile is sorted before it is written to file, and that if a * barcode's data does span multiple tiles, data collected from each tile must be written in the order of the tiles * themselves. * <p/> * This class employs a number of private subclasses to achieve this goal. The TileReadAggregator controls the flow * of operation. It is fed a number of Tiles which it uses to spawn TileReaders. TileReaders are responsible for * reading Illumina data for their respective tiles from disk, and as they collect that data, it is fed back into the * TileReadAggregator. When a TileReader completes a tile, it notifies the TileReadAggregator, which reviews what was * read and conditionally queues its writing to disk, baring in mind the requirements of write-order described in the * previous paragraph. As writes complete, the TileReadAggregator re-evalutes the state of reads/writes and may queue * more writes. When all barcodes for all tiles have been written, the TileReadAggregator shuts down. * <p/> * The TileReadAggregator controls task execution using a specialized ThreadPoolExecutor. It accepts special Runnables * of type PriorityRunnable which allow a priority to be assigned to the runnable. When the ThreadPoolExecutor is * assigning threads, it gives priority to those PriorityRunnables with higher priority values. In this application, * TileReaders are assigned lowest priority, and write tasks are assigned high priority. It is designed in this fashion * to minimize the amount of time data must remain in memory (write the data as soon as possible, then discard it from * memory) while maximizing CPU usage. * * @author jburke@broadinstitute.org * @author mccowan@broadinstitute.org */ public class IlluminaBasecallsToSam extends CommandLineProgram { // The following attributes define the command-line arguments @Usage public String USAGE = getStandardUsagePreamble() + "Generate a SAM or BAM file from data in an Illumina basecalls output directory.\n"; @Option(doc = "The basecalls output directory. ", shortName = "B") public File BASECALLS_DIR; @Option(doc = "Lane number. ", shortName = StandardOptionDefinitions.LANE_SHORT_NAME) public Integer LANE; @Option(doc = "Deprecated (use LIBRARY_PARAMS). The output SAM or BAM file. Format is determined by extension.", shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, mutex = {"BARCODE_PARAMS", "LIBRARY_PARAMS"}) public File OUTPUT; @Option(doc = "Prefixed to read names.") public String RUN_BARCODE; @Option(doc = "Deprecated (use LIBRARY_PARAMS). The name of the sequenced sample", shortName = StandardOptionDefinitions.SAMPLE_ALIAS_SHORT_NAME, mutex = {"BARCODE_PARAMS", "LIBRARY_PARAMS"}) public String SAMPLE_ALIAS; @Option(doc = "ID used to link RG header record with RG tag in SAM record. " + "If these are unique in SAM files that get merged, merge performance is better. " + "If not specified, READ_GROUP_ID = <first 5 chars of RUN_BARCODE>.<LANE> .", shortName = StandardOptionDefinitions.READ_GROUP_ID_SHORT_NAME, optional = true) public String READ_GROUP_ID; @Option(doc = "Deprecated (use LIBRARY_PARAMS). The name of the sequenced library", shortName = StandardOptionDefinitions.LIBRARY_NAME_SHORT_NAME, optional = true, mutex = {"BARCODE_PARAMS", "LIBRARY_PARAMS"}) public String LIBRARY_NAME; @Option(doc = "The name of the sequencing center that produced the reads to fill in the RG.CN tag.", optional = true) public String SEQUENCING_CENTER = "BI"; @Option(doc = "The start date of the run.", optional = true) public Date RUN_START_DATE; @Option(doc = "The name of the sequencing technology that produced the read.", optional = true) public String PLATFORM = "illumina"; @Option(doc = ReadStructure.PARAMETER_DOC, shortName = "RS") public String READ_STRUCTURE; @Option(doc = "Deprecated (use LIBRARY_PARAMS). Tab-separated file for creating all output BAMs for barcoded run " + "with single IlluminaBasecallsToSam invocation. Columns are BARCODE, OUTPUT, SAMPLE_ALIAS, and " + "LIBRARY_NAME. Row with BARCODE=N is used to specify a file for no barcode match", mutex = {"OUTPUT", "SAMPLE_ALIAS", "LIBRARY_NAME", "LIBRARY_PARAMS"}) public File BARCODE_PARAMS; @Option(doc = "Tab-separated file for creating all output BAMs for a run with single IlluminaBasecallsToSam " + "invocation. TheColumns are OUTPUT, SAMPLE_ALIAS, and LIBRARY_NAME, BARCODE_1, BARCODE_2 ... BARCODE_X " + "where X = number of barcodes per cluster (optional). Row with BARCODE_1=N is used to specify a file " + "for no barcode match. You may also provide any 2 letter RG header attributes (excluding PU, CN, PL, and" + " DT) as columns in this file and the values for those columns will be inserted into the RG tag for the" + " BAM file created for a given row.", mutex = {"OUTPUT", "SAMPLE_ALIAS", "LIBRARY_NAME", "BARCODE_PARAMS"}) public File LIBRARY_PARAMS; @Option(doc = "Which adapters to look for in the read.") public List<IlluminaAdapterPair> ADAPTERS_TO_CHECK = new ArrayList<IlluminaAdapterPair>( Arrays.asList(IlluminaAdapterPair.INDEXED, IlluminaAdapterPair.DUAL_INDEXED, IlluminaAdapterPair.NEXTERA_V2)); @Option(doc = "Run this many threads in parallel. If NUM_PROCESSORS = 0, number of cores is automatically set to " + "the number of cores available on the machine. If NUM_PROCESSORS < 0, then the number of cores used will" + " be the number available on the machine less NUM_PROCESSORS.") public Integer NUM_PROCESSORS = 0; @Option(doc = "If set, this is the first tile to be processed (for debugging). Note that tiles are not processed" + " in numerical order.", optional = true) public Integer FIRST_TILE; @Option(doc = "If set, process no more than this many tiles (for debugging).", optional = true) public Integer TILE_LIMIT; @Option(doc = "If true, call System.gc() periodically. This is useful in cases in which the -Xmx value passed " + "is larger than the available memory. Default: true.", optional = true) public Boolean FORCE_GC = true; @Option(doc = "Configure SortingCollections to store this many records before spilling to disk. For an indexed" + " run, each SortingCollection gets this value/number of indices.") public int MAX_READS_IN_RAM_PER_TILE = 1200000; private final Map<String, SAMFileWriter> barcodeSamWriterMap = new HashMap<String, SAMFileWriter>(); private IlluminaBasecallsToSamConverter converter; private IlluminaDataProviderFactory factory; private ReadStructure readStructure; private int numThreads; private final Comparator<SAMRecord> samRecordQueryNameComparator = new SAMRecordQueryNameComparator(); private List<Integer> tiles; public static final IlluminaDataType[] DATA_TYPES_NO_BARCODE = {IlluminaDataType.BaseCalls, IlluminaDataType.QualityScores, IlluminaDataType.Position, IlluminaDataType.PF}; private static final IlluminaDataType[] DATA_TYPES_WITH_BARCODE = Arrays.copyOf(DATA_TYPES_NO_BARCODE, DATA_TYPES_NO_BARCODE.length + 1); private static final Log log = Log.getInstance(IlluminaBasecallsToSam.class); private final ProgressLogger readProgressLogger = new ProgressLogger(log, 1000000, "Read"); private final ProgressLogger writeProgressLogger = new ProgressLogger(log, 1000000, "Write"); /** * Describes the state of a barcode's data's processing in the context of a tile. It is either not available in * that tile, has been read, has been queued to be written to file, or has been written to file. A barcode only * takes on a state once the tile (which is serving as the context of this state) has been read. */ private enum TileBarcodeProcessingState { NA, READ, QUEUED_FOR_WRITE, WRITTEN } /** * Describes the state of a tile being processed. It is either not yet completely read, or read. */ private enum TileProcessingState { NOT_DONE_READING, DONE_READING } /** * A comparator for tile numbers, which are not necessarily ordered by the number's value. */ public static final Comparator<Integer> TILE_NUMBER_COMPARATOR = new Comparator<Integer>() { @Override public int compare(final Integer integer1, final Integer integer2) { final String s1 = integer1.toString(); final String s2 = integer2.toString(); // Because a the tile number is followed by a colon, a tile number that // is a prefix of another tile number should sort after. (e.g. 10 sorts after 100). if (s1.length() < s2.length()) { if (s2.startsWith(s1)) { return 1; } } else if (s2.length() < s1.length()) { if (s1.startsWith(s2)) { return -1; } } return s1.compareTo(s2); } }; static { DATA_TYPES_WITH_BARCODE[DATA_TYPES_WITH_BARCODE.length - 1] = IlluminaDataType.Barcodes; } /** * Simple representation of a tile */ private class Tile implements Comparable<Tile> { private final int tileNumber; public Tile(final int i) { tileNumber = i; } public int getNumber() { return tileNumber; } @Override public boolean equals(final Object o) { return o instanceof Tile && this.getNumber() == ((Tile) o).getNumber(); } @Override public int compareTo(final Tile o) { return TILE_NUMBER_COMPARATOR.compare(this.getNumber(), o.getNumber()); } } /** * Reads the information from a tile via an IlluminaDataProvider and feeds red information into a processingRecord * managed by the TileReadAggregator. */ private class TileReader { private final Tile tile; private final TileReadAggregator handler; private final TileProcessingRecord processingRecord; public TileReader(final Tile tile, final TileReadAggregator handler, final TileProcessingRecord processingRecord) { this.tile = tile; this.handler = handler; this.processingRecord = processingRecord; } /** * Reads the data from the appropriate IlluminaDataProvider and feeds it into the TileProcessingRecord for * this tile. */ public void process() { final IlluminaDataProvider dataProvider = factory.makeDataProvider(Arrays.asList(this.tile.getNumber())); final SAMRecord[] recordContainer = new SAMRecord[converter.getNumRecordsPerCluster()]; log.debug(String.format("Reading data from tile %s ...", tile.getNumber())); while (dataProvider.hasNext()) { final ClusterData cluster = dataProvider.next(); final String barcode = cluster.getMatchedBarcode(); converter.createSamRecords(cluster, null, recordContainer); for (final SAMRecord record : recordContainer) { readProgressLogger.record(record); this.processingRecord.addRecord(barcode, record); } } this.handler.completeTile(this.tile); } } /** * Represents the state of a tile's processing and encapsulates the data collected from that tile */ private class TileProcessingRecord { final private Map<String, SortingCollection<SAMRecord>> barcodeToRecordCollection = new HashMap<String, SortingCollection<SAMRecord>>(); final private Map<String, TileBarcodeProcessingState> barcodeToProcessingState = new HashMap<String, TileBarcodeProcessingState>(); private TileProcessingState state = TileProcessingState.NOT_DONE_READING; private long recordCount = 0; /** * Returns the state of this tile's processing. */ public TileProcessingState getState() { return this.state; } /** * Sets the state of this tile's processing. */ public void setState(final TileProcessingState state) { this.state = state; } /** * Adds the provided recoded to this tile. */ public void addRecord(final String barcode, final SAMRecord... records) { this.recordCount += records.length; // Grab the existing collection, or initialize it if it doesn't yet exist SortingCollection<SAMRecord> recordCollection = this.barcodeToRecordCollection.get(barcode); if (recordCollection == null) { recordCollection = this.newSortingCollection(); this.barcodeToRecordCollection.put(barcode, recordCollection); this.barcodeToProcessingState.put(barcode, null); } for (final SAMRecord record : records) { recordCollection.add(record); } } private SortingCollection<SAMRecord> newSortingCollection() { final int maxRecordsInRam = IlluminaBasecallsToSam.this.MAX_READS_IN_RAM_PER_TILE / IlluminaBasecallsToSam.this.barcodeSamWriterMap.size(); return SortingCollection.newInstance( SAMRecord.class, new BAMRecordCodec(null), new SAMRecordQueryNameComparator(), maxRecordsInRam, IlluminaBasecallsToSam.this.TMP_DIR); } /** * Returns the number of unique barcodes read. */ public long getBarcodeCount() { return this.barcodeToRecordCollection.size(); } /** * Returns the number of records read. */ public long getRecordCount() { return recordCount; } /** * Returns the mapping of barcodes to records associated with them. */ public Map<String, SortingCollection<SAMRecord>> getBarcodeRecords() { return barcodeToRecordCollection; } public TileBarcodeProcessingState getBarcodeState(final String barcode) { if (this.getState() == TileProcessingState.NOT_DONE_READING) { throw new IllegalStateException( "A tile's barcode data's state cannot be queried until the tile has been completely read."); } if (this.barcodeToProcessingState.containsKey(barcode)) { return this.barcodeToProcessingState.get(barcode); } else { return TileBarcodeProcessingState.NA; } } /** * Sets the processing state of the provided barcode in this record. * * @throws NoSuchElementException When the provided barcode is not one associated with this record. */ public void setBarcodeState(final String barcode, final TileBarcodeProcessingState state) { if (this.barcodeToProcessingState.containsKey(barcode)) { this.barcodeToProcessingState.put(barcode, state); } else { throw new NoSuchElementException(String.format("No record of the provided barcode, %s.", barcode)); } } /** * Returns the distinct set of barcodes for which data has been collected in this record. * * @return */ public Set<String> getBarcodes() { return this.getBarcodeRecords().keySet(); } } /** * Aggregates data collected from tiles and writes them to file. Accepts records from TileReaders and maps * them to the appropriate BAM writers. */ private class TileReadAggregator { /** * The collection of records associated with a particular tile. * <p/> * Implemented as a TreeMap to guarantee tiles are iterated over in natural order. */ private final Map<Tile, TileProcessingRecord> tileRecords = new TreeMap<Tile, TileProcessingRecord>(); /** * The executor responsible for doing work. * <p/> * Implemented as a ThreadPoolExecutor with a PriorityBlockingQueue which orders submitted Runnables by their * priority. */ private final ExecutorService prioritizingThreadPool = new ThreadPoolExecutor( IlluminaBasecallsToSam.this.numThreads, IlluminaBasecallsToSam.this.numThreads, 0L, MILLISECONDS, new PriorityBlockingQueue<Runnable>(5, new Comparator<Runnable>() { @Override /** * Compare the two Runnables, and assume they are PriorityRunnable; if not something strange is * going on, so allow a ClassCastException be thrown. */ public int compare(final Runnable o1, final Runnable o2) { // Higher priority items go earlier in the queue, so reverse the "natural" comparison. return ((PriorityRunnable) o2).getPriority() - ((PriorityRunnable) o1).getPriority(); } })); /** * The object acting as a latch to notify when the aggregator completes its work. */ private final Object completionLatch = new Object(); /** * Stores the thread that is executing this work so that it can be interrupted upon failure. */ private Thread parentThread; private final Object workEnqueueMonitor = new Object(); private final AtomicBoolean submitted = new AtomicBoolean(false); /** * Creates a TileReadAggregator that reads from the provided tiles. * * @param tiles */ public TileReadAggregator(final Collection<Tile> tiles) { for (final Tile t : tiles) { tileRecords.put(t, new TileProcessingRecord()); } } public void submit() { // Ensure the aggregator as not yet been submitted if (!this.submitted.compareAndSet(false, true)) { throw new IllegalStateException("The submit() method may not be called more than once."); } // Set the thread that is executing this work this.parentThread = Thread.currentThread(); /** * For each tile, create and submit a tile processor. Give it a negative execution priority (so that * prioritized tasks with a positive execution priority execute first), and give later tiles a lesser * (more negative) priority. */ int priority = 0; for (final Tile tile : this.tileRecords.keySet()) { final TileReader reader = new TileReader(tile, this, this.tileRecords.get(tile)); this.prioritizingThreadPool.execute(new PriorityRunnable(--priority) { @Override public void run() { try { reader.process(); } catch (RuntimeException e) { /** * In the event of an internal failure, signal to the parent thread that something has gone * wrong. This is necessary because if an item of work fails to complete, the aggregator will * will never reach its completed state, and it will never terminate. */ parentThread.interrupt(); throw e; } catch (Error e) { parentThread.interrupt(); throw e; } } }); } } private void completeTile(final Tile tile) { final TileProcessingRecord tileRecord = this.tileRecords.get(tile); if (tileRecord.getState() == TileProcessingState.DONE_READING) { throw new IllegalStateException("This tile is already in the completed state."); } // Update all of the barcodes and the tile to be marked as read for (final String barcode : tileRecord.getBarcodes()) { tileRecord.setBarcodeState(barcode, TileBarcodeProcessingState.READ); } tileRecord.setState(TileProcessingState.DONE_READING); log.debug(String.format("Completed reading tile %s; collected %s reads spanning %s barcodes.", tile.getNumber(), tileRecord.getRecordCount(), tileRecord.getBarcodeCount())); //noinspection SynchronizationOnLocalVariableOrMethodParameter this.findAndEnqueueWorkOrSignalCompletion(); } /** * Blocks until this aggregator completes its work. * * @throws InterruptedException */ public void awaitWorkComplete() throws InterruptedException { synchronized (this.completionLatch) { this.completionLatch.wait(); } } /** * Signals to any thread awaiting via awaitWorkComplete() that no work remains. Called * when this aggregator has reached its completed state. */ private void signalWorkComplete() { synchronized (this.completionLatch) { this.completionLatch.notifyAll(); } } /** * Poll the aggregator to find more tasks for it to enqueue. Specifically, searches for un-written data * read from tiles for each barcode and enqueues it for writing. */ private void findAndEnqueueWorkOrSignalCompletion() { synchronized (this.workEnqueueMonitor) { /** * If there is work remaining to be done in this aggregator, walk through all of the barcodes and find * tiles which have not yet written their barcode data but are in a state where they are able to. */ if (this.isWorkCompleted()) { this.signalWorkComplete(); } else { final Queue<Runnable> tasks = new LinkedList<Runnable>(); for (final String barcode : barcodeSamWriterMap.keySet()) { NEXT_BARCODE: for (final Map.Entry<Tile, TileProcessingRecord> entry : this.tileRecords.entrySet()) { final Tile tile = entry.getKey(); final TileProcessingRecord tileRecord = entry.getValue(); /** * If this tile has not been read, we cannot write this or later tiles' barcode data; * move to the next barcode. */ if (tileRecord.getState() != TileProcessingState.DONE_READING) { break NEXT_BARCODE; } switch (tileRecord.getBarcodeState(barcode)) { case NA: case WRITTEN: /** * There is no data for this barcode for this tile, or it is already written; in * either scenario, this barcode will not be processed further for this tile, so * move onto the next tile as a possible candidate. */ continue; case QUEUED_FOR_WRITE: /** * The write for this barcode is in progress for this tile, so skip to the next * barcode. */ break NEXT_BARCODE; case READ: /** * This barcode has beenr read, and all of the earlier tiles have been written * for this barcode, so queue its writing. */ tileRecord.setBarcodeState(barcode, TileBarcodeProcessingState.QUEUED_FOR_WRITE); log.debug(String.format("Enqueuing work for tile %s and barcode %s.", tile.getNumber(), barcode)); tasks.add(this.newBarcodeWorkInstance(tile, tileRecord, barcode)); break NEXT_BARCODE; } } } for (final Runnable task : tasks) { this.prioritizingThreadPool.execute(task); } } } } /** * Returns a PriorityRunnable that encapsulates the work involved with writing the provided tileRecord's data * for the given barcode to disk. * * @param tile The tile from which the record was read * @param tileRecord The processing record associated with the tile * @param barcode The barcode whose data within the tileRecord is to be written * @return The runnable that upon invocation writes the barcode's data from the tileRecord to disk */ private PriorityRunnable newBarcodeWorkInstance(final Tile tile, final TileProcessingRecord tileRecord, final String barcode) { return new PriorityRunnable() { @Override public void run() { try { final SortingCollection<SAMRecord> records = tileRecord.getBarcodeRecords().get(barcode); final SAMFileWriter writer = barcodeSamWriterMap.get(barcode); log.debug(String.format("Writing records from tile %s with barcode %s ...", tile.getNumber(), barcode)); final PeekIterator<SAMRecord> it = new PeekIterator<SAMRecord>(records.iterator()); while (it.hasNext()) { final SAMRecord rec = it.next(); /** * PIC-330 Sometimes there are two reads with the same cluster coordinates, and thus * the same read name. Discard both of them. This code assumes that the two first of pairs * will come before the two second of pairs, so it isn't necessary to look ahead a different * distance for paired end. It also assumes that for paired ends there will be duplicates * for both ends, so there is no need to be PE-aware. */ if (it.hasNext()) { final SAMRecord lookAhead = it.peek(); if (!rec.getReadUnmappedFlag() || !lookAhead.getReadUnmappedFlag()) { throw new IllegalStateException("Should not have mapped reads."); } if (samRecordQueryNameComparator.compare(rec, lookAhead) == 0) { it.next(); log.info("Skipping reads with identical read names: " + rec.getReadName()); continue; } } writer.addAlignment(rec); writeProgressLogger.record(rec); } tileRecord.setBarcodeState(barcode, TileBarcodeProcessingState.WRITTEN); findAndEnqueueWorkOrSignalCompletion(); } catch (RuntimeException e) { /** * In the event of an internal failure, signal to the parent thread that something has gone * wrong. This is necessary because if an item of work fails to complete, the aggregator will * will never reach its completed state, and it will never terminate. */ parentThread.interrupt(); throw e; } catch (Error e) { parentThread.interrupt(); throw e; } } }; } /** * Returns true if this aggregator has not completed its work. Specifically, returns false iff * any tile's barcode data yas not yet been written. * * @return True if more work remains to be done, false otherwise */ public boolean isWorkCompleted() { for (final Map.Entry<Tile, TileProcessingRecord> entry : this.tileRecords.entrySet()) { final TileProcessingRecord tileProcessingRecord = entry.getValue(); if (tileProcessingRecord.getState() != TileProcessingState.DONE_READING) { return false; } else { for (final TileBarcodeProcessingState barcodeProcessingState : tileProcessingRecord.barcodeToProcessingState.values()) { if (barcodeProcessingState != TileBarcodeProcessingState.WRITTEN) { return false; } } } } return true; } /** * Terminates the threads currently exiting in the thread pool abruptly via ThreadPoolExecutor.shutdownNow(). */ public void shutdown() { this.prioritizingThreadPool.shutdownNow(); } } /** * A Runnable that carries a priority which is used to compare and order other PriorityRunnables in a task queue. */ private abstract class PriorityRunnable implements Runnable { private final int priority; /** * Create a new priority runnable with a default priority of 1. */ public PriorityRunnable() { this(1); } public PriorityRunnable(final int priority) { this.priority = priority; } /** * Returns the priority level. Higher priorities are run earlier. * * @return */ int getPriority() { return this.priority; } } @Override protected int doWork() { initialize(); doTileProcessing(); finalise(); return 0; } /** * Closes the SAMFileWriters in barcodeSamWriterMap. * <p/> * This method is intentionally misspelled to avoid conflict with Object.finalize(); */ private void finalise() { // Close the writers for (final Map.Entry<String, SAMFileWriter> entry : barcodeSamWriterMap.entrySet()) { final SAMFileWriter writer = entry.getValue(); log.debug(String.format("Closing file for barcode %s.", entry.getKey())); writer.close(); } } /** * Prepares loggers, initiates garbage collection thread, parses arguments and initialized variables appropriately/ */ private void initialize() { if (OUTPUT != null) { IoUtil.assertFileIsWritable(OUTPUT); } if (LIBRARY_PARAMS != null) { IoUtil.assertFileIsReadable(LIBRARY_PARAMS); } // If we're forcing garbage collection, collect every 5 minutes in a daemon thread. if (this.FORCE_GC) { final Timer gcTimer = new Timer(true); final long delay = 5 * 1000 * 60; gcTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("Before explicit GC, Runtime.totalMemory()=" + Runtime.getRuntime().totalMemory()); System.gc(); System.runFinalization(); System.out.println("After explicit GC, Runtime.totalMemory()=" + Runtime.getRuntime().totalMemory()); } }, delay, delay); } readStructure = new ReadStructure(READ_STRUCTURE); factory = new IlluminaDataProviderFactory(BASECALLS_DIR, LANE, readStructure, getDataTypesFromReadStructure(readStructure)); log.info("DONE_READING STRUCTURE IS " + readStructure.toString()); this.tiles = new ArrayList<Integer>(factory.getAvailableTiles()); // Since the first non-fixed part of the read name is the tile number, without preceding zeroes, // and the output is sorted by read name, process the tiles in this order. Collections.sort(tiles, TILE_NUMBER_COMPARATOR); if (FIRST_TILE != null) { int i; for (i = 0; i < tiles.size(); ++i) { if (tiles.get(i).intValue() == FIRST_TILE.intValue()) { tiles = tiles.subList(i, tiles.size()); break; } } if (tiles.get(0).intValue() != FIRST_TILE.intValue()) { throw new PicardException("FIRST_TILE=" + FIRST_TILE + ", but that tile was not found."); } } if (TILE_LIMIT != null && tiles.size() > TILE_LIMIT) { tiles = tiles.subList(0, TILE_LIMIT); } if (OUTPUT != null) { barcodeSamWriterMap.put(null, buildSamFileWriter(OUTPUT, SAMPLE_ALIAS, LIBRARY_NAME, buildSamHeaderParameters(null))); } else { populateWritersFromLibraryParams(); } /** * Be sure to pass the outputReadStructure to IlluminaBasecallsToSamConverter, which reflects the structure of the output cluster * data which may be different from the input read structure (specifically if there are skips). */ converter = new IlluminaBasecallsToSamConverter(RUN_BARCODE, READ_GROUP_ID, factory.getOutputReadStructure(), ADAPTERS_TO_CHECK); if (NUM_PROCESSORS == 0) { this.numThreads = Runtime.getRuntime().availableProcessors(); } else if (NUM_PROCESSORS < 0) { this.numThreads = Runtime.getRuntime().availableProcessors() + NUM_PROCESSORS; } else { this.numThreads = NUM_PROCESSORS; } this.numThreads = Math.max(1, Math.min(this.numThreads, tiles.size())); } private void doTileProcessing() { // TODO: Eliminate this when switch to JDK 7 FileChannelJDKBugWorkAround.doBugWorkAround(); // Generate the list of tiles that will be processed final List<Tile> tiles = new ArrayList<Tile>(); for (final Integer tileNumber : this.tiles) { tiles.add(new Tile(tileNumber)); } final TileReadAggregator tileReadAggregator = new TileReadAggregator(tiles); tileReadAggregator.submit(); try { tileReadAggregator.awaitWorkComplete(); } catch (InterruptedException e) { log.error(e, "Failure encountered in worker thread; attempting to shut down remaining worker threads and terminate ..."); tileReadAggregator.shutdown(); } } /** * Assert that expectedCols are present and return actualCols - expectedCols * * @param actualCols The columns present in the LIBRARY_PARAMS file * @param expectedCols The columns that are REQUIRED * @return actualCols - expectedCols */ private Set<String> findAndFilterExpectedColumns(final Set<String> actualCols, final Set<String> expectedCols) { final Set<String> missingColumns = new HashSet<String>(expectedCols); missingColumns.removeAll(actualCols); if (missingColumns.size() > 0) { throw new PicardException(String.format( "LIBRARY_PARAMS file %s is missing the following columns: %s.", LIBRARY_PARAMS.getAbsolutePath(), StringUtil.join(", ", missingColumns ))); } final Set<String> remainingColumns = new HashSet<String>(actualCols); remainingColumns.removeAll(expectedCols); return remainingColumns; } /** * Given a set of columns assert that all columns conform to the format of an RG header attribute (i.e. 2 letters) * the attribute is NOT a member of the rgHeaderTags that are built by default in buildSamHeaderParameters * * @param rgTagColumns A set of columns that should conform to the rg header attribute format */ private void checkRgTagColumns(final Set<String> rgTagColumns) { final Set<String> forbiddenHeaders = buildSamHeaderParameters(null).keySet(); forbiddenHeaders.retainAll(rgTagColumns); if (forbiddenHeaders.size() > 0) { throw new PicardException("Illegal ReadGroup tags in library params(barcode params) file(" + LIBRARY_PARAMS.getAbsolutePath() + ") Offending headers = " + StringUtil.join(", ", forbiddenHeaders)); } for (final String column : rgTagColumns) { if (column.length() > 2) { throw new PicardException("Column label (" + column + ") unrecognized. Library params(barcode params) can only contain the columns " + "(OUTPUT, LIBRARY_NAME, SAMPLE_ALIAS, BARCODE, BARCODE_<X> where X is a positive integer) OR two letter RG tags!"); } } } /** * For each line in the LIBRARY_PARAMS file create a SamFileWriter and put it in the barcodeSamWriterMap map, where * the key to the map is the concatenation of all barcodes in order for the given line */ private void populateWritersFromLibraryParams() { final TabbedTextFileWithHeaderParser libraryParamsParser = new TabbedTextFileWithHeaderParser(LIBRARY_PARAMS); final Set<String> expectedColumnLabels = CollectionUtil.makeSet("OUTPUT", "SAMPLE_ALIAS", "LIBRARY_NAME"); final List<String> barcodeColumnLabels = new ArrayList<String>(); if (readStructure.barcodes.length() == 1) { //For the single barcode read case, the barcode label name can either by BARCODE or BARCODE_1 if (libraryParamsParser.hasColumn("BARCODE")) { barcodeColumnLabels.add("BARCODE"); } else if (libraryParamsParser.hasColumn("BARCODE_1")) { barcodeColumnLabels.add("BARCODE_1"); } else { throw new PicardException("LIBRARY_PARAMS(BARCODE_PARAMS) file " + LIBRARY_PARAMS + " does not have column BARCODE or BARCODE_1."); } } else { for (int i = 1; i <= readStructure.barcodes.length(); i++) { barcodeColumnLabels.add("BARCODE_" + i); } } expectedColumnLabels.addAll(barcodeColumnLabels); final Set<String> rgTagColumns = findAndFilterExpectedColumns(libraryParamsParser.columnLabels(), expectedColumnLabels); checkRgTagColumns(rgTagColumns); for (final TabbedTextFileWithHeaderParser.Row row : libraryParamsParser) { List<String> barcodeValues = null; if (barcodeColumnLabels.size() > 0) { barcodeValues = new ArrayList<String>(); for (final String barcodeLabel : barcodeColumnLabels) { barcodeValues.add(row.getField(barcodeLabel)); } } final String key = (barcodeValues == null || barcodeValues.contains("N")) ? null : StringUtil.join("", barcodeValues); if (barcodeSamWriterMap.containsKey(key)) { //This will catch the case of having more than 1 line in a non-barcoded LIBRARY_PARAMS file throw new PicardException("Row for barcode " + key + " appears more than once in LIBRARY_PARAMS or BARCODE_PARAMS file " + LIBRARY_PARAMS); } final Map<String, String> samHeaderParams = buildSamHeaderParameters(barcodeValues); for (final String tagName : rgTagColumns) { samHeaderParams.put(tagName, row.getField(tagName)); } final SAMFileWriter writer = buildSamFileWriter(new File(row.getField("OUTPUT")), row.getField("SAMPLE_ALIAS"), row.getField("LIBRARY_NAME"), samHeaderParams); barcodeSamWriterMap.put(key, writer); } if (barcodeSamWriterMap.isEmpty()) { throw new PicardException("LIBRARY_PARAMS(BARCODE_PARAMS) file " + LIBRARY_PARAMS + " does have any data rows."); } } /** * Create the list of headers that will be added to the SAMFileHeader for a library with the given barcodes (or * the entire run if barcodes == NULL). Note that any value that is null will NOT be added via buildSamFileWriter * but is placed in the map in order to be able to query the tags that we automatically add. * * @param barcodes The list of barcodes that uniquely identify the read group we are building parameters for * @return A Map of ReadGroupHeaderTags -> Values */ private Map<String, String> buildSamHeaderParameters(final List<String> barcodes) { final Map<String, String> params = new HashMap<String, String>(); String platformUnit = RUN_BARCODE + "." + LANE; if (barcodes != null) platformUnit += ("." + IlluminaUtil.barcodeSeqsToString(barcodes)); params.put("PU", platformUnit); params.put("CN", SEQUENCING_CENTER); params.put("PL", PLATFORM); if (RUN_START_DATE != null) { final Iso8601Date date = new Iso8601Date(RUN_START_DATE); params.put("DT", date.toString()); } else { params.put("DT", null); } return params; } /** * Build a SamFileWriter that will output it's contents to output. * * @param output The file to which to write * @param sampleAlias The sample alias set in the read group header * @param libraryName The name of the library to which this read group belongs * @param headerParameters Header parameters that will be added to the RG header for this SamFile * @return A SAMFileWriter */ private SAMFileWriter buildSamFileWriter(final File output, final String sampleAlias, final String libraryName, final Map<String, String> headerParameters) { IoUtil.assertFileIsWritable(output); final SAMReadGroupRecord rg = new SAMReadGroupRecord(READ_GROUP_ID); rg.setSample(sampleAlias); if (libraryName != null) rg.setLibrary(libraryName); for (final Map.Entry<String, String> tagNameToValue : headerParameters.entrySet()) { if (tagNameToValue.getValue() != null) { rg.setAttribute(tagNameToValue.getKey(), tagNameToValue.getValue()); } } final SAMFileHeader header = new SAMFileHeader(); header.setSortOrder(SAMFileHeader.SortOrder.queryname); header.addReadGroup(rg); return new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, output); } public static void main(final String[] args) { System.exit(new IlluminaBasecallsToSam().instanceMain(args)); } /** * Put any custom command-line validation in an override of this method. * clp is initialized at this point and can be used to print usage and access args. * Any options set by command-line parser can be validated. * * @return null if command line is valid. If command line is invalid, returns an array of error message * to be written to the appropriate place. */ @Override protected String[] customCommandLineValidation() { if (BARCODE_PARAMS != null) { LIBRARY_PARAMS = BARCODE_PARAMS; } final ArrayList<String> messages = new ArrayList<String>(); readStructure = new ReadStructure(READ_STRUCTURE); if (!readStructure.barcodes.isEmpty()) { if (LIBRARY_PARAMS == null) { messages.add("BARCODE_PARAMS or LIBRARY_PARAMS is missing. If READ_STRUCTURE contains a B (barcode)" + " then either LIBRARY_PARAMS or BARCODE_PARAMS(deprecated) must be provided!"); } } if (READ_GROUP_ID == null) { READ_GROUP_ID = RUN_BARCODE.substring(0, 5) + "." + LANE; } if (messages.size() == 0) { return null; } return messages.toArray(new String[messages.size()]); } /** * Given a read structure return the data types that need to be parsed for this run */ private static IlluminaDataType[] getDataTypesFromReadStructure(final ReadStructure readStructure) { if (readStructure.barcodes.isEmpty()) { return DATA_TYPES_NO_BARCODE; } else { return DATA_TYPES_WITH_BARCODE; } } }