answer
stringlengths
17
10.2M
//$HeadURL$ package org.deegree.feature.persistence.sql; import static org.deegree.commons.xml.CommonNamespaces.OGCNS; import static org.deegree.commons.xml.CommonNamespaces.XLNNS; import static org.deegree.commons.xml.CommonNamespaces.XSINS; import static org.slf4j.LoggerFactory.getLogger; import java.lang.reflect.Constructor; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import javax.xml.namespace.QName; import org.deegree.commons.annotations.LoggingNotes; import org.deegree.commons.jdbc.ResultSetIterator; import org.deegree.commons.jdbc.SQLIdentifier; import org.deegree.commons.jdbc.TableName; import org.deegree.commons.tom.CombinedReferenceResolver; import org.deegree.commons.tom.TypedObjectNode; import org.deegree.commons.tom.gml.GMLObject; import org.deegree.commons.tom.gml.GMLReferenceResolver; import org.deegree.commons.tom.primitive.BaseType; import org.deegree.commons.tom.primitive.PrimitiveType; import org.deegree.commons.tom.primitive.PrimitiveValue; import org.deegree.commons.tom.sql.ParticleConverter; import org.deegree.commons.tom.sql.SQLValueMangler; import org.deegree.commons.utils.JDBCUtils; import org.deegree.commons.utils.Pair; import org.deegree.commons.utils.kvp.InvalidParameterValueException; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.db.ConnectionProvider; import org.deegree.db.ConnectionProviderProvider; import org.deegree.feature.Feature; import org.deegree.feature.Features; import org.deegree.feature.persistence.FeatureInspector; import org.deegree.feature.persistence.FeatureStore; import org.deegree.feature.persistence.FeatureStoreException; import org.deegree.feature.persistence.FeatureStoreGMLIdResolver; import org.deegree.feature.persistence.FeatureStoreManager; import org.deegree.feature.persistence.FeatureStoreTransaction; import org.deegree.feature.persistence.cache.BBoxCache; import org.deegree.feature.persistence.cache.FeatureStoreCache; import org.deegree.feature.persistence.cache.SimpleFeatureStoreCache; import org.deegree.feature.persistence.lock.DefaultLockManager; import org.deegree.feature.persistence.lock.LockManager; import org.deegree.feature.persistence.query.Query; import org.deegree.feature.persistence.sql.blob.BlobCodec; import org.deegree.feature.persistence.sql.blob.BlobMapping; import org.deegree.feature.persistence.sql.blob.FeatureBuilderBlob; import org.deegree.feature.persistence.sql.config.AbstractMappedSchemaBuilder; import org.deegree.feature.persistence.sql.converter.CustomParticleConverter; import org.deegree.feature.persistence.sql.converter.FeatureParticleConverter; import org.deegree.feature.persistence.sql.id.FIDMapping; import org.deegree.feature.persistence.sql.id.IdAnalysis; import org.deegree.feature.persistence.sql.jaxb.CustomConverterJAXB; import org.deegree.feature.persistence.sql.jaxb.CustomInspector; import org.deegree.feature.persistence.sql.jaxb.SQLFeatureStoreJAXB; import org.deegree.feature.persistence.sql.rules.CompoundMapping; import org.deegree.feature.persistence.sql.rules.FeatureBuilderRelational; import org.deegree.feature.persistence.sql.rules.FeatureMapping; import org.deegree.feature.persistence.sql.rules.GeometryMapping; import org.deegree.feature.persistence.sql.rules.Mapping; import org.deegree.feature.persistence.sql.rules.PrimitiveMapping; import org.deegree.feature.stream.CombinedFeatureInputStream; import org.deegree.feature.stream.EmptyFeatureInputStream; import org.deegree.feature.stream.FeatureInputStream; import org.deegree.feature.stream.FilteredFeatureInputStream; import org.deegree.feature.stream.IteratorFeatureInputStream; import org.deegree.feature.stream.MemoryFeatureInputStream; import org.deegree.feature.types.FeatureType; import org.deegree.feature.types.property.GeometryPropertyType.CoordinateDimension; import org.deegree.feature.types.property.GeometryPropertyType.GeometryType; import org.deegree.filter.Filter; import org.deegree.filter.FilterEvaluationException; import org.deegree.filter.IdFilter; import org.deegree.filter.OperatorFilter; import org.deegree.filter.expression.ValueReference; import org.deegree.filter.sort.SortProperty; import org.deegree.filter.spatial.BBOX; import org.deegree.geometry.Envelope; import org.deegree.geometry.Geometry; import org.deegree.geometry.GeometryTransformer; import org.deegree.protocol.wfs.getfeature.TypeName; import org.deegree.sqldialect.SQLDialect; import org.deegree.sqldialect.filter.AbstractWhereBuilder; import org.deegree.sqldialect.filter.DBField; import org.deegree.sqldialect.filter.Join; import org.deegree.sqldialect.filter.MappingExpression; import org.deegree.sqldialect.filter.PropertyNameMapper; import org.deegree.sqldialect.filter.PropertyNameMapping; import org.deegree.sqldialect.filter.TableAliasManager; import org.deegree.sqldialect.filter.UnmappableException; import org.deegree.sqldialect.filter.expression.SQLArgument; import org.deegree.sqldialect.filter.expression.SQLExpression; import org.deegree.workspace.Resource; import org.deegree.workspace.ResourceInitException; import org.deegree.workspace.ResourceMetadata; import org.deegree.workspace.Workspace; import org.slf4j.Logger; /** * {@link FeatureStore} that is backed by a spatial SQL database. * * @see SQLDialect * * @author <a href="mailto:schneider@occamlabs.de">Markus Schneider</a> * * @since 3.2 */ @LoggingNotes(info = "logs particle converter initialization", debug = "logs the SQL statements sent to the SQL server and startup/shutdown information") public class SQLFeatureStore implements FeatureStore { private static final Logger LOG = getLogger( SQLFeatureStore.class ); private static final int DEFAULT_FETCH_SIZE = 1000; private static final int DEFAULT_CACHE_SIZE = 10000; private final SQLFeatureStoreJAXB config; private final URL configURL; private final SQLDialect dialect; private final boolean allowInMemoryFiltering; private MappedAppSchema schema; private BlobMapping blobMapping; private final String jdbcConnId; private final Map<Mapping, ParticleConverter<?>> particleMappingToConverter = new HashMap<Mapping, ParticleConverter<?>>(); private final FeatureStoreCache cache; private BBoxCache bboxCache; private GMLReferenceResolver resolver = new FeatureStoreGMLIdResolver( this ); private Map<String, String> nsContext; private DefaultLockManager lockManager; private final int fetchSize; private final Boolean readAutoCommit; private final List<FeatureInspector> inspectors = new ArrayList<FeatureInspector>(); private boolean nullEscalation; private final SqlFeatureStoreMetadata metadata; private final Workspace workspace; private ConnectionProvider connProvider; private final ThreadLocal<SQLFeatureStoreTransaction> transaction = new ThreadLocal<SQLFeatureStoreTransaction>(); /** * Creates a new {@link SQLFeatureStore} for the given configuration. * * @param config * jaxb configuration object * @param configURL * configuration systemid */ public SQLFeatureStore( SQLFeatureStoreJAXB config, URL configURL, SQLDialect dialect, SqlFeatureStoreMetadata metadata, Workspace workspace ) { this.config = config; this.configURL = configURL; this.dialect = dialect; this.metadata = metadata; this.workspace = workspace; this.jdbcConnId = config.getJDBCConnId().getValue(); this.allowInMemoryFiltering = config.getDisablePostFiltering() == null; fetchSize = config.getJDBCConnId().getFetchSize() != null ? config.getJDBCConnId().getFetchSize().intValue() : DEFAULT_FETCH_SIZE; LOG.debug( "Fetch size: " + fetchSize ); readAutoCommit = config.getJDBCConnId().isReadAutoCommit() != null ? config.getJDBCConnId().isReadAutoCommit() : !dialect.requiresTransactionForCursorMode(); LOG.debug( "Read auto commit: " + readAutoCommit ); if ( config.getFeatureCache() != null ) { cache = new SimpleFeatureStoreCache( DEFAULT_CACHE_SIZE ); } else { cache = null; } } private void initConverters() { for ( FeatureType ft : schema.getFeatureTypes() ) { FeatureTypeMapping ftMapping = schema.getFtMapping( ft.getName() ); if ( ftMapping != null ) { for ( Mapping particleMapping : ftMapping.getMappings() ) { initConverter( particleMapping ); } } } } private void initConverter( Mapping particleMapping ) { if ( particleMapping.getConverter() != null ) { CustomParticleConverter<TypedObjectNode> converter = instantiateConverter( particleMapping.getConverter() ); converter.init( particleMapping, this ); particleMappingToConverter.put( particleMapping, converter ); } else if ( particleMapping instanceof PrimitiveMapping ) { PrimitiveMapping pm = (PrimitiveMapping) particleMapping; ParticleConverter<?> converter = dialect.getPrimitiveConverter( pm.getMapping().toString(), pm.getType() ); particleMappingToConverter.put( particleMapping, converter ); } else if ( particleMapping instanceof GeometryMapping ) { GeometryMapping gm = (GeometryMapping) particleMapping; ParticleConverter<?> converter = getGeometryConverter( gm ); particleMappingToConverter.put( particleMapping, converter ); } else if ( particleMapping instanceof FeatureMapping ) { FeatureMapping fm = (FeatureMapping) particleMapping; SQLIdentifier fkColumn = null; if ( fm.getJoinedTable() != null && !fm.getJoinedTable().isEmpty() ) { // TODO more complex joins fkColumn = fm.getJoinedTable().get( fm.getJoinedTable().size() - 1 ).getFromColumns().get( 0 ); } SQLIdentifier hrefColumn = null; if ( fm.getHrefMapping() != null ) { hrefColumn = new SQLIdentifier( fm.getHrefMapping().toString() ); } FeatureType valueFt = null; if ( fm.getValueFtName() != null ) { valueFt = schema.getFeatureType( fm.getValueFtName() ); } ParticleConverter<?> converter = new FeatureParticleConverter( fkColumn, hrefColumn, getResolver(), valueFt, schema ); particleMappingToConverter.put( particleMapping, converter ); } else if ( particleMapping instanceof CompoundMapping ) { CompoundMapping cm = (CompoundMapping) particleMapping; for ( Mapping childMapping : cm.getParticles() ) { initConverter( childMapping ); } } else { LOG.warn( "Unhandled particle mapping type {}", particleMapping ); } } ParticleConverter<Geometry> getGeometryConverter( GeometryMapping geomMapping ) { String column = geomMapping.getMapping().toString(); ICRS crs = geomMapping.getCRS(); String srid = geomMapping.getSrid(); boolean is2d = geomMapping.getDim() == CoordinateDimension.DIM_2; return dialect.getGeometryConverter( column, crs, srid, is2d ); } @SuppressWarnings("unchecked") private CustomParticleConverter<TypedObjectNode> instantiateConverter( CustomConverterJAXB config ) { String className = config.getClazz(); LOG.info( "Instantiating configured custom particle converter (class=" + className + ")" ); try { return (CustomParticleConverter<TypedObjectNode>) workspace.getModuleClassLoader().loadClass( className ).newInstance(); } catch ( Throwable t ) { String msg = "Unable to instantiate custom particle converter (class=" + className + "). " + " Maybe directory 'modules' in your workspace is missing the JAR with the " + " referenced converter class?! " + t.getMessage(); LOG.error( msg, t ); throw new IllegalArgumentException( msg ); } } @Override public MappedAppSchema getSchema() { return schema; } @Override public boolean isMapped( QName ftName ) { if ( schema.getFtMapping( ftName ) != null ) { return true; } if ( schema.getBBoxMapping() != null ) { return true; } return false; } public String getConnId() { return jdbcConnId; } /** * Returns the relational mapping for the given feature type name. * * @param ftName * name of the feature type, must not be <code>null</code> * @return relational mapping for the feature type, may be <code>null</code> (no relational mapping) */ public FeatureTypeMapping getMapping( QName ftName ) { return schema.getFtMapping( ftName ); } /** * Returns a {@link ParticleConverter} for the given {@link Mapping} instance from the served * {@link MappedAppSchema}. * * @param mapping * particle mapping, must not be <code>null</code> * @return particle converter, never <code>null</code> */ public ParticleConverter<?> getConverter( Mapping mapping ) { return particleMappingToConverter.get( mapping ); } @Override public Envelope getEnvelope( QName ftName ) throws FeatureStoreException { if ( !bboxCache.contains( ftName ) ) { calcEnvelope( ftName ); } return bboxCache.get( ftName ); } @Override public Envelope calcEnvelope( QName ftName ) throws FeatureStoreException { Envelope env = null; Connection conn = null; try { conn = getConnection(); env = calcEnvelope( ftName, conn ); } catch ( SQLException e ) { throw new FeatureStoreException( e.getMessage() ); } finally { release( null, null, conn ); } return env; } Envelope calcEnvelope( QName ftName, Connection conn ) throws FeatureStoreException { Envelope env = null; FeatureType ft = schema.getFeatureType( ftName ); if ( ft != null ) { // TODO what should be favored for hybrid mappings? if ( blobMapping != null ) { env = calcEnvelope( ftName, blobMapping, conn ); } else if ( schema.getFtMapping( ft.getName() ) != null ) { FeatureTypeMapping ftMapping = schema.getFtMapping( ft.getName() ); env = calcEnvelope( ftMapping, conn ); } } bboxCache.set( ftName, env ); return env; } private Envelope calcEnvelope( FeatureTypeMapping ftMapping, Connection conn ) throws FeatureStoreException { LOG.trace( "Determining BBOX for feature type '{}' (relational mode)", ftMapping.getFeatureType() ); String column = null; Pair<TableName, GeometryMapping> propMapping = ftMapping.getDefaultGeometryMapping(); if ( propMapping == null ) { return null; } MappingExpression me = propMapping.second.getMapping(); if ( me == null || !( me instanceof DBField ) ) { String msg = "Cannot determine BBOX for feature type '" + ftMapping.getFeatureType() + "' (relational mode)."; LOG.warn( msg ); return null; } column = ( (DBField) me ).getColumn(); Envelope env = null; StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( dialect.getBBoxAggregateSnippet( column ) ); sql.append( " FROM " ); sql.append( propMapping.first ); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); LOG.debug( "Executing envelope SELECT: " + sql ); rs = stmt.executeQuery( sql.toString() ); rs.next(); ICRS crs = propMapping.second.getCRS(); env = dialect.getBBoxAggregateValue( rs, 1, crs ); } catch ( SQLException e ) { LOG.debug( e.getMessage(), e ); throw new FeatureStoreException( e.getMessage(), e ); } finally { release( rs, stmt, null ); } return env; } private Envelope calcEnvelope( QName ftName, BlobMapping blobMapping, Connection conn ) throws FeatureStoreException { LOG.debug( "Determining BBOX for feature type '{}' (BLOB mode)", ftName ); int ftId = getFtId( ftName ); String column = blobMapping.getBBoxColumn(); Envelope env = null; StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( dialect.getBBoxAggregateSnippet( column ) ); sql.append( " FROM " ); sql.append( blobMapping.getTable() ); sql.append( " WHERE " ); sql.append( blobMapping.getTypeColumn() ); sql.append( "=" ); sql.append( ftId ); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery( sql.toString() ); rs.next(); ICRS crs = blobMapping.getCRS(); env = dialect.getBBoxAggregateValue( rs, 1, crs ); } catch ( SQLException e ) { LOG.debug( e.getMessage(), e ); throw new FeatureStoreException( e.getMessage(), e ); } finally { release( rs, stmt, null ); } return env; } BBoxCache getBBoxCache() { return bboxCache; } @Override public GMLObject getObjectById( String id ) throws FeatureStoreException { GMLObject geomOrFeature = null; if ( getCache() != null ) { geomOrFeature = getCache().get( id ); } if ( geomOrFeature == null ) { if ( getSchema().getBlobMapping() != null ) { geomOrFeature = getObjectByIdBlob( id, getSchema().getBlobMapping() ); } else { geomOrFeature = getObjectByIdRelational( id ); } } return geomOrFeature; } private GMLObject getObjectByIdBlob( String id, BlobMapping blobMapping ) throws FeatureStoreException { GMLObject geomOrFeature = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( blobMapping.getDataColumn() ); sql.append( " FROM " ); sql.append( blobMapping.getTable() ); sql.append( " WHERE " ); sql.append( blobMapping.getGMLIdColumn() ); sql.append( "=?" ); conn = getConnection(); stmt = conn.prepareStatement( sql.toString() ); stmt.setFetchSize( fetchSize ); stmt.setString( 1, id ); rs = stmt.executeQuery(); if ( rs.next() ) { LOG.debug( "Recreating object '" + id + "' from bytea." ); BlobCodec codec = blobMapping.getCodec(); geomOrFeature = codec.decode( rs.getBinaryStream( 1 ), getNamespaceContext(), getSchema(), blobMapping.getCRS(), resolver ); if ( getCache() != null ) { getCache().add( geomOrFeature ); } } } catch ( Exception e ) { String msg = "Error retrieving object by id (BLOB mode): " + e.getMessage(); LOG.debug( msg, e ); throw new FeatureStoreException( msg, e ); } finally { release( rs, stmt, conn ); } return geomOrFeature; } private GMLObject getObjectByIdRelational( String id ) throws FeatureStoreException { GMLObject result = null; IdAnalysis idAnalysis = getSchema().analyzeId( id ); if ( !idAnalysis.isFid() ) { String msg = "Fetching of geometries by id (relational mode) is not implemented yet."; throw new UnsupportedOperationException( msg ); } FeatureInputStream rs = queryByIdFilterRelational( null, new IdFilter( id ), null ); try { Iterator<Feature> iter = rs.iterator(); if ( iter.hasNext() ) { result = iter.next(); } } finally { rs.close(); } return result; } @Override public LockManager getLockManager() throws FeatureStoreException { return lockManager; } @Override public FeatureStoreTransaction acquireTransaction() throws FeatureStoreException { SQLFeatureStoreTransaction ta = null; try { final Connection conn = getConnection(); conn.setAutoCommit( false ); ta = new SQLFeatureStoreTransaction( this, conn, getSchema(), inspectors ); transaction.set( ta ); } catch ( SQLException e ) { throw new FeatureStoreException( "Unable to acquire JDBC connection for transaction: " + e.getMessage(), e ); } return ta; } void closeAndDetachTransactionConnection() throws FeatureStoreException { try { transaction.get().getConnection().close(); } catch ( final SQLException e ) { LOG.error( "Error closing connection/removing it from the pool: " + e.getMessage() ); } finally { transaction.remove(); } } /** * Returns the {@link FeatureStoreCache}. * * @return feature store cache, can be <code>null</code> (no cache configured) */ public FeatureStoreCache getCache() { return cache; } /** * Returns a resolver instance for resolving references to objects that are stored in this feature store. * * @return resolver, never <code>null</code> */ public GMLReferenceResolver getResolver() { return resolver; } @Override public boolean isAvailable() { return true; } @Override public void destroy() { // nothing to do } @Override public int queryHits( Query query ) throws FeatureStoreException, FilterEvaluationException { if ( query.getTypeNames() == null || query.getTypeNames().length > 1 ) { String msg = "Join queries between multiple feature types are not supported by the SQLFeatureStore implementation (yet)."; throw new UnsupportedOperationException( msg ); } Filter filter = query.getFilter(); int hits = 0; if ( query.getTypeNames().length == 1 && ( filter == null || filter instanceof OperatorFilter ) ) { QName ftName = query.getTypeNames()[0].getFeatureTypeName(); FeatureType ft = getSchema().getFeatureType( ftName ); if ( ft == null ) { String msg = "Feature type '" + ftName + "' is not served by this feature store."; throw new FeatureStoreException( msg ); } hits = queryHitsByOperatorFilter( query, ftName, (OperatorFilter) filter ); } else { // must be an id filter based query if ( query.getFilter() == null || !( query.getFilter() instanceof IdFilter ) ) { String msg = "Invalid query. If no type names are specified, it must contain an IdFilter."; throw new FilterEvaluationException( msg ); } // should be no problem iterating over the features (id queries usually request only a few ids) hits = queryByIdFilter( query.getTypeNames(), (IdFilter) filter, query.getSortProperties() ).count(); } return hits; } private int queryHitsByOperatorFilter( Query query, QName ftName, OperatorFilter filter ) throws FeatureStoreException { LOG.debug( "Performing hits query by operator filter" ); if ( getSchema().getBlobMapping() != null ) { return queryHitsByOperatorFilterBlob( query, ftName, filter ); } FeatureType ft = getSchema().getFeatureType( ftName ); FeatureTypeMapping ftMapping = getMapping( ftName ); if ( ftMapping == null ) { String msg = "Cannot perform query on feature type '" + ftName + "'. Feature type is not mapped."; throw new FeatureStoreException( msg ); } int hits = 0; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); AbstractWhereBuilder wb = getWhereBuilder( ft, filter, query.getSortProperties(), conn ); if ( wb.getPostFilter() != null ) { LOG.debug( "Filter not fully mappable to WHERE clause. Need to iterate over all features to determine count." ); hits = queryByOperatorFilter( query, ftName, filter ).count(); } else { StringBuilder sql = new StringBuilder( "SELECT " ); if ( wb.getWhere() == null ) { sql.append( "COUNT(*) FROM " ); sql.append( ftMapping.getFtTable() ); } else { sql.append( "COUNT(*) FROM (SELECT DISTINCT " ); String ftTableAlias = wb.getAliasManager().getRootTableAlias(); FIDMapping fidMapping = ftMapping.getFidMapping(); List<Pair<SQLIdentifier, BaseType>> fidCols = fidMapping.getColumns(); boolean first = true; for ( Pair<SQLIdentifier, BaseType> fidCol : fidCols ) { if ( !first ) { sql.append( "," ); } else { first = false; } sql.append( ftTableAlias ).append( '.' ).append( fidCol.first ); } sql.append( " FROM " ); // pure relational query sql.append( ftMapping.getFtTable() ); sql.append( ' ' ); sql.append( ftTableAlias ); for ( PropertyNameMapping mappedPropName : wb.getMappedPropertyNames() ) { for ( Join join : mappedPropName.getJoins() ) { sql.append( " LEFT OUTER JOIN " ); sql.append( join.getToTable() ); sql.append( ' ' ); sql.append( join.getToTableAlias() ); sql.append( " ON " ); sql.append( join.getSQLJoinCondition() ); } } LOG.debug( "WHERE clause: " + wb.getWhere() ); if ( wb.getWhere() != null ) { sql.append( " WHERE " ); sql.append( wb.getWhere().getSQL() ); } sql.append( ") featureids" ); } LOG.debug( "SQL: {}", sql ); long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; if ( wb.getWhere() != null ) { for ( SQLArgument o : wb.getWhere().getArguments() ) { o.setArgument( stmt, i++ ); } } begin = System.currentTimeMillis(); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); rs.next(); hits = rs.getInt( 1 ); } } catch ( Exception e ) { String msg = "Error performing hits query by operator filter: " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } finally { release( rs, stmt, conn ); } return hits; } private int queryHitsByOperatorFilterBlob( Query query, QName ftName, OperatorFilter filter ) throws FeatureStoreException { LOG.debug( "Performing blob query (hits) by operator filter" ); AbstractWhereBuilder wb = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; int hits = 0; try { conn = getConnection(); BlobMapping blobMapping = getSchema().getBlobMapping(); if ( query.getPrefilterBBox() != null ) { OperatorFilter bboxFilter = new OperatorFilter( query.getPrefilterBBox() ); wb = getWhereBuilderBlob( bboxFilter, conn ); LOG.debug( "WHERE clause: " + wb.getWhere() ); } String alias = wb != null ? wb.getAliasManager().getRootTableAlias() : "X1"; StringBuilder sql = new StringBuilder( "SELECT COUNT(*) FROM " ); sql.append( blobMapping.getTable() ); sql.append( ' ' ); sql.append( alias ); sql.append( " WHERE " ); sql.append( alias ); sql.append( "." ); sql.append( blobMapping.getTypeColumn() ); sql.append( "=?" ); if ( wb != null ) { sql.append( " AND " ); sql.append( wb.getWhere().getSQL() ); } LOG.debug( "SQL: {}", sql ); long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; stmt.setShort( i++, getSchema().getFtId( ftName ) ); if ( wb != null ) { for ( SQLArgument o : wb.getWhere().getArguments() ) { o.setArgument( stmt, i++ ); } } begin = System.currentTimeMillis(); rs = stmt.executeQuery(); stmt.setFetchSize( fetchSize ); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); rs.next(); hits = rs.getInt( 1 ); } catch ( Exception e ) { String msg = "Error performing query by operator filter: " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } finally { release( rs, stmt, conn ); } return hits; } @Override public int[] queryHits( Query[] queries ) throws FeatureStoreException, FilterEvaluationException { int[] hits = new int[queries.length]; for ( int i = 0; i < queries.length; i++ ) { hits[i] = queryHits( queries[i] ); } return hits; } public Map<String, String> getNamespaceContext() { if ( nsContext == null ) { nsContext = new HashMap<String, String>( getSchema().getNamespaceBindings() ); nsContext.put( "xlink", XLNNS ); nsContext.put( "xsi", XSINS ); nsContext.put( "ogc", OGCNS ); } return nsContext; } /** * Returns a transformed version of the given {@link Geometry} in the specified CRS. * * @param literal * @param crs * @return transformed version of the geometry, never <code>null</code> * @throws FilterEvaluationException */ public static Geometry getCompatibleGeometry( Geometry literal, ICRS crs ) throws FilterEvaluationException { if ( crs == null ) { return literal; } Geometry transformedLiteral = literal; if ( literal != null ) { ICRS literalCRS = literal.getCoordinateSystem(); if ( literalCRS != null && !( crs.equals( literalCRS ) ) ) { LOG.debug( "Need transformed literal geometry for evaluation: " + literalCRS.getAlias() + " -> " + crs.getAlias() ); try { GeometryTransformer transformer = new GeometryTransformer( crs ); transformedLiteral = transformer.transform( literal ); } catch ( Exception e ) { throw new FilterEvaluationException( e.getMessage() ); } } } return transformedLiteral; } short getFtId( QName ftName ) { return getSchema().getFtId( ftName ); } @Override public FeatureInputStream query( Query query ) throws FeatureStoreException, FilterEvaluationException { if ( query.getTypeNames() == null || query.getTypeNames().length > 1 ) { String msg = "Join queries between multiple feature types are not by SQLFeatureStore (yet)."; throw new UnsupportedOperationException( msg ); } FeatureInputStream result = null; Filter filter = query.getFilter(); if ( query.getTypeNames().length == 1 && ( filter == null || filter instanceof OperatorFilter ) ) { QName ftName = query.getTypeNames()[0].getFeatureTypeName(); FeatureType ft = getSchema().getFeatureType( ftName ); if ( ft == null ) { String msg = "Feature store is not configured to serve feature type '" + ftName + "'."; throw new FeatureStoreException( msg ); } result = queryByOperatorFilter( query, ftName, (OperatorFilter) filter ); } else { // must be an id filter based query if ( query.getFilter() == null || !( query.getFilter() instanceof IdFilter ) ) { String msg = "Invalid query. If no type names are specified, it must contain an IdFilter."; throw new FilterEvaluationException( msg ); } result = queryByIdFilter( query.getTypeNames(), (IdFilter) filter, query.getSortProperties() ); } return result; } @Override public FeatureInputStream query( final Query[] queries ) throws FeatureStoreException, FilterEvaluationException { // check for common case: multiple featuretypes, same bbox (WMS), no other filter constraints boolean wmsStyleQuery = false; Envelope env = queries[0].getPrefilterBBoxEnvelope(); if ( getSchema().getBlobMapping() != null && queries[0].getFilter() == null && queries[0].getSortProperties().length == 0 ) { wmsStyleQuery = true; for ( int i = 1; i < queries.length; i++ ) { Envelope queryBBox = queries[i].getPrefilterBBoxEnvelope(); if ( queryBBox != env && queries[i].getFilter() != null && queries[i].getSortProperties() != null ) { wmsStyleQuery = false; break; } } } if ( wmsStyleQuery ) { return queryMultipleFts( queries, env ); } Iterator<FeatureInputStream> rsIter = new Iterator<FeatureInputStream>() { int i = 0; @Override public boolean hasNext() { return i < queries.length; } @Override public FeatureInputStream next() { if ( !hasNext() ) { throw new NoSuchElementException(); } FeatureInputStream rs; try { rs = query( queries[i++] ); } catch ( InvalidParameterValueException e ) { throw e; } catch ( Throwable e ) { LOG.debug( e.getMessage(), e ); throw new RuntimeException( e.getMessage(), e ); } return rs; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new CombinedFeatureInputStream( rsIter ); } private FeatureInputStream queryByIdFilter( TypeName[] typeNames, IdFilter filter, SortProperty[] sortCrit ) throws FeatureStoreException { if ( blobMapping != null ) { return queryByIdFilterBlob( filter, sortCrit ); } return queryByIdFilterRelational( typeNames, filter, sortCrit ); } private FeatureInputStream queryByIdFilterBlob( IdFilter filter, SortProperty[] sortCrit ) throws FeatureStoreException { FeatureInputStream result = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); StringBuilder sb = new StringBuilder( filter.getMatchingIds().size() * 2 ); sb.append( "?" ); for ( int i = 1; i < filter.getMatchingIds().size(); ++i ) { sb.append( ",?" ); } long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( "SELECT gml_id,binary_object FROM " + blobMapping.getTable() + " A WHERE A.gml_id in (" + sb + ")" ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); stmt.setFetchSize( fetchSize ); int idx = 0; for ( String id : filter.getMatchingIds() ) { stmt.setString( ++idx, id ); } begin = System.currentTimeMillis(); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); FeatureBuilder builder = new FeatureBuilderBlob( this, blobMapping ); result = new IteratorFeatureInputStream( new FeatureResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { release( rs, stmt, conn ); String msg = "Error performing id query: " + e.getMessage(); LOG.debug( msg, e ); throw new FeatureStoreException( msg, e ); } // sort features if ( sortCrit.length > 0 ) { result = new MemoryFeatureInputStream( Features.sortFc( result.toCollection(), sortCrit ) ); } return result; } private FeatureInputStream queryByIdFilterRelational( TypeName[] typeNames, IdFilter filter, SortProperty[] sortCrit ) throws FeatureStoreException { LinkedHashMap<QName, List<IdAnalysis>> ftNameToIdAnalysis = new LinkedHashMap<QName, List<IdAnalysis>>(); try { for ( String fid : filter.getMatchingIds() ) { IdAnalysis analysis = getSchema().analyzeId( fid ); FeatureType ft = analysis.getFeatureType(); List<IdAnalysis> idKernels = ftNameToIdAnalysis.get( ft.getName() ); if ( idKernels == null ) { idKernels = new ArrayList<IdAnalysis>(); ftNameToIdAnalysis.put( ft.getName(), idKernels ); } idKernels.add( analysis ); } } catch ( IllegalArgumentException e ) { LOG.warn( "No features are returned, as an error occurred during mapping of feature name to id: " + e.getMessage() ); LOG.trace( e.getMessage(), e ); return new EmptyFeatureInputStream(); } if ( ftNameToIdAnalysis.size() != 1 ) { throw new FeatureStoreException( "Currently, only relational id queries are supported that target single feature types." ); } QName ftName = ftNameToIdAnalysis.keySet().iterator().next(); FeatureType ft = getSchema().getFeatureType( ftName ); checkIfFeatureTypIsRequested( typeNames, ft ); FeatureTypeMapping ftMapping = getSchema().getFtMapping( ftName ); FIDMapping fidMapping = ftMapping.getFidMapping(); List<IdAnalysis> idKernels = ftNameToIdAnalysis.get( ftName ); FeatureInputStream result = null; PreparedStatement stmt = null; ResultSet rs = null; Connection conn = null; try { long begin = System.currentTimeMillis(); conn = getConnection(); String tableAlias = "X1"; FeatureBuilder builder = new FeatureBuilderRelational( this, ft, ftMapping, conn, tableAlias, nullEscalation ); List<String> columns = builder.getInitialSelectList(); StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( columns.get( 0 ) ); for ( int i = 1; i < columns.size(); i++ ) { sql.append( ',' ); sql.append( columns.get( i ) ); } sql.append( " FROM " ); sql.append( ftMapping.getFtTable() ); sql.append( ' ' ); sql.append( tableAlias ); sql.append( " WHERE " ); boolean first = true; for ( IdAnalysis idKernel : idKernels ) { if ( !first ) { sql.append( " OR " ); } sql.append( "(" ); boolean firstCol = true; for ( Pair<SQLIdentifier, BaseType> fidColumn : fidMapping.getColumns() ) { if ( !firstCol ) { sql.append( " AND " ); } sql.append( fidColumn.first ); sql.append( "=?" ); firstCol = false; } sql.append( ")" ); first = false; } LOG.debug( "SQL: {}", sql ); stmt = conn.prepareStatement( sql.toString() ); stmt.setFetchSize( fetchSize ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; for ( IdAnalysis idKernel : idKernels ) { int j = 0; for ( Object o : idKernel.getIdKernels() ) { PrimitiveType pt = new PrimitiveType( fidMapping.getColumns().get( j++ ).getSecond() ); PrimitiveValue value = new PrimitiveValue( o, pt ); Object sqlValue = SQLValueMangler.internalToSQL( value ); stmt.setObject( i++, sqlValue ); } } begin = System.currentTimeMillis(); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); result = new IteratorFeatureInputStream( new FeatureResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { release( rs, stmt, conn ); String msg = "Error performing query by id filter (relational mode): " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } return result; } protected Connection getConnection() throws SQLException { if ( isTransactionActive() ) { return transaction.get().getConnection(); } final Connection conn = connProvider.getConnection(); conn.setAutoCommit( readAutoCommit ); return conn; } private void release( final ResultSet rs, final Statement stmt, final Connection conn ) { if ( isTransactionActive() ) { JDBCUtils.close( rs, stmt, null, LOG ); } else { JDBCUtils.close( rs, stmt, conn, LOG ); } } private boolean isTransactionActive() { return transaction.get() != null; } private FeatureInputStream queryByOperatorFilterBlob( Query query, QName ftName, OperatorFilter filter ) throws FeatureStoreException { LOG.debug( "Performing blob query by operator filter" ); AbstractWhereBuilder wb = null; Connection conn = null; FeatureInputStream result = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = getConnection(); FeatureTypeMapping ftMapping = getMapping( ftName ); BlobMapping blobMapping = getSchema().getBlobMapping(); FeatureBuilder builder = new FeatureBuilderBlob( this, blobMapping ); List<String> columns = builder.getInitialSelectList(); wb = getWhereBuilderBlob( filter, conn ); final SQLExpression where = wb.getWhere(); LOG.debug( "WHERE clause: " + where ); String alias = wb.getAliasManager().getRootTableAlias(); StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( columns.get( 0 ) ); for ( int i = 1; i < columns.size(); i++ ) { sql.append( ',' ); sql.append( columns.get( i ) ); } sql.append( " FROM " ); if ( ftMapping == null ) { // pure BLOB query sql.append( blobMapping.getTable() ); sql.append( ' ' ); sql.append( alias ); // } else { // hybrid query // sql.append( blobMapping.getTable() ); // sql.append( ' ' ); // sql.append( alias ); // sql.append( " LEFT OUTER JOIN " ); // sql.append( ftMapping.getFtTable() ); // sql.append( ' ' ); // sql.append( alias ); // sql.append( " ON " ); // sql.append( alias ); // sql.append( "." ); // sql.append( blobMapping.getInternalIdColumn() ); // sql.append( "=" ); // sql.append( alias ); // sql.append( "." ); // sql.append( ftMapping.getFidMapping().getColumn() ); } if ( wb != null ) { for ( PropertyNameMapping mappedPropName : wb.getMappedPropertyNames() ) { for ( Join join : mappedPropName.getJoins() ) { sql.append( " LEFT OUTER JOIN " ); sql.append( join.getToTable() ); sql.append( ' ' ); sql.append( join.getToTableAlias() ); sql.append( " ON " ); sql.append( join.getSQLJoinCondition() ); } } } sql.append( " WHERE " ); sql.append( alias ); sql.append( "." ); sql.append( blobMapping.getTypeColumn() ); sql.append( "=?" ); if ( wb != null ) { sql.append( " AND " ); sql.append( wb.getWhere().getSQL() ); } // if ( wb != null && wb.getWhere() != null ) { // if ( blobMapping != null ) { // sql.append( " AND " ); // } else { // sql.append( " WHERE " ); // sql.append( wb.getWhere().getSQL() ); // if ( wb != null && wb.getOrderBy() != null ) { // sql.append( " ORDER BY " ); // sql.append( wb.getOrderBy().getSQL() ); LOG.debug( "SQL: {}", sql ); long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; // if ( blobMapping != null ) { stmt.setShort( i++, getSchema().getFtId( ftName ) ); if ( wb != null ) { for ( SQLArgument o : wb.getWhere().getArguments() ) { o.setArgument( stmt, i++ ); } } // if ( wb != null && wb.getWhere() != null ) { // for ( SQLArgument o : wb.getWhere().getArguments() ) { // o.setArgument( stmt, i++ ); // if ( wb != null && wb.getOrderBy() != null ) { // for ( SQLArgument o : wb.getOrderBy().getArguments() ) { // o.setArgument( stmt, i++ ); begin = System.currentTimeMillis(); stmt.setFetchSize( fetchSize ); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); result = new IteratorFeatureInputStream( new FeatureResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { release( rs, stmt, conn ); String msg = "Error performing query by operator filter: " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } if ( filter != null ) { LOG.debug( "Applying in-memory post-filtering." ); result = new FilteredFeatureInputStream( result, filter ); } if ( query.getSortProperties().length > 0 ) { LOG.debug( "Applying in-memory post-sorting." ); result = new MemoryFeatureInputStream( Features.sortFc( result.toCollection(), query.getSortProperties() ) ); } return result; } private FeatureInputStream queryByOperatorFilter( Query query, QName ftName, OperatorFilter filter ) throws FeatureStoreException { LOG.debug( "Performing query by operator filter" ); if ( getSchema().getBlobMapping() != null ) { return queryByOperatorFilterBlob( query, ftName, filter ); } AbstractWhereBuilder wb = null; Connection conn = null; FeatureInputStream result = null; PreparedStatement stmt = null; ResultSet rs = null; FeatureType ft = getSchema().getFeatureType( ftName ); FeatureTypeMapping ftMapping = getMapping( ftName ); if ( ftMapping == null ) { String msg = "Cannot perform query on feature type '" + ftName + "'. Feature type is not mapped."; throw new FeatureStoreException( msg ); } try { conn = getConnection(); wb = getWhereBuilder( ft, filter, query.getSortProperties(), conn ); String ftTableAlias = wb.getAliasManager().getRootTableAlias(); LOG.debug( "WHERE clause: " + wb.getWhere() ); LOG.debug( "ORDER BY clause: " + wb.getOrderBy() ); FeatureBuilder builder = new FeatureBuilderRelational( this, ft, ftMapping, conn, ftTableAlias, nullEscalation ); List<String> columns = builder.getInitialSelectList(); BlobMapping blobMapping = getSchema().getBlobMapping(); StringBuilder sql = new StringBuilder( "SELECT " ); sql.append( columns.get( 0 ) ); for ( int i = 1; i < columns.size(); i++ ) { sql.append( ',' ); sql.append( columns.get( i ) ); } sql.append( " FROM " ); // pure relational query sql.append( ftMapping.getFtTable() ); sql.append( ' ' ); sql.append( ftTableAlias ); for ( PropertyNameMapping mappedPropName : wb.getMappedPropertyNames() ) { for ( Join join : mappedPropName.getJoins() ) { sql.append( " LEFT OUTER JOIN " ); sql.append( join.getToTable() ); sql.append( ' ' ); sql.append( join.getToTableAlias() ); sql.append( " ON " ); sql.append( join.getSQLJoinCondition() ); } } if ( wb.getWhere() != null ) { if ( blobMapping != null ) { sql.append( " AND " ); } else { sql.append( " WHERE " ); } sql.append( wb.getWhere().getSQL() ); } if ( wb.getOrderBy() != null ) { sql.append( " ORDER BY " ); sql.append( wb.getOrderBy().getSQL() ); } LOG.debug( "SQL: {}", sql ); long begin = System.currentTimeMillis(); stmt = conn.prepareStatement( sql.toString() ); LOG.debug( "Preparing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); int i = 1; if ( wb.getWhere() != null ) { for ( SQLArgument o : wb.getWhere().getArguments() ) { o.setArgument( stmt, i++ ); } } if ( wb.getOrderBy() != null ) { for ( SQLArgument o : wb.getOrderBy().getArguments() ) { o.setArgument( stmt, i++ ); } } begin = System.currentTimeMillis(); stmt.setFetchSize( fetchSize ); rs = stmt.executeQuery(); LOG.debug( "Executing SELECT took {} [ms] ", System.currentTimeMillis() - begin ); result = new IteratorFeatureInputStream( new FeatureResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { release( rs, stmt, conn ); String msg = "Error performing query by operator filter: " + e.getMessage(); LOG.error( msg, e ); throw new FeatureStoreException( msg, e ); } if ( wb.getPostFilter() != null ) { LOG.debug( "Applying in-memory post-filtering." ); result = new FilteredFeatureInputStream( result, wb.getPostFilter() ); } if ( wb.getPostSortCriteria() != null ) { LOG.debug( "Applying in-memory post-sorting." ); result = new MemoryFeatureInputStream( Features.sortFc( result.toCollection(), wb.getPostSortCriteria() ) ); } return result; } private FeatureInputStream queryMultipleFts( Query[] queries, Envelope looseBBox ) throws FeatureStoreException { FeatureInputStream result = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; AbstractWhereBuilder blobWb = null; try { if ( looseBBox != null ) { final OperatorFilter bboxFilter = new OperatorFilter( new BBOX( looseBBox ) ); blobWb = getWhereBuilderBlob( bboxFilter, conn ); } conn = getConnection(); final short[] ftId = getQueriedFeatureTypeIds( queries ); final StringBuilder sql = new StringBuilder(); for ( int i = 0; i < ftId.length; i++ ) { if ( i > 0 ) { sql.append( " UNION " ); } sql.append( "SELECT gml_id,binary_object" ); if ( ftId.length > 1 ) { sql.append( "," ); sql.append( i ); sql.append( " AS QUERY_POS" ); } sql.append( " FROM " ); sql.append( blobMapping.getTable() ); sql.append( " WHERE ft_type=?" ); if ( looseBBox != null ) { sql.append( " AND gml_bounded_by && ?" ); } } if ( ftId.length > 1 ) { sql.append( " ORDER BY QUERY_POS" ); } stmt = conn.prepareStatement( sql.toString() ); stmt.setFetchSize( fetchSize ); int argIdx = 1; for ( final short ftId2 : ftId ) { stmt.setShort( argIdx++, ftId2 ); if ( blobWb != null && blobWb.getWhere() != null ) { for ( SQLArgument o : blobWb.getWhere().getArguments() ) { o.setArgument( stmt, argIdx++ ); } } } LOG.debug( "Query: {}", sql ); LOG.debug( "Prepared: {}", stmt ); rs = stmt.executeQuery(); final FeatureBuilder builder = new FeatureBuilderBlob( this, blobMapping ); result = new IteratorFeatureInputStream( new FeatureResultSetIterator( builder, rs, conn, stmt ) ); } catch ( Exception e ) { release( rs, stmt, conn ); String msg = "Error performing query: " + e.getMessage(); LOG.debug( msg ); LOG.trace( "Stack trace:", e ); throw new FeatureStoreException( msg, e ); } return result; } private short[] getQueriedFeatureTypeIds( Query[] queries ) { short[] ftId = new short[queries.length]; for ( int i = 0; i < ftId.length; i++ ) { Query query = queries[i]; if ( query.getTypeNames() == null || query.getTypeNames().length > 1 ) { String msg = "Join queries between multiple feature types are currently not supported."; throw new UnsupportedOperationException( msg ); } ftId[i] = getFtId( query.getTypeNames()[0].getFeatureTypeName() ); } return ftId; } private AbstractWhereBuilder getWhereBuilder( FeatureType ft, OperatorFilter filter, SortProperty[] sortCrit, Connection conn ) throws FilterEvaluationException, UnmappableException { PropertyNameMapper mapper = new SQLPropertyNameMapper( this, getMapping( ft.getName() ) ); return dialect.getWhereBuilder( mapper, filter, sortCrit, allowInMemoryFiltering ); } private AbstractWhereBuilder getWhereBuilderBlob( OperatorFilter filter, Connection conn ) throws FilterEvaluationException, UnmappableException { final String undefinedSrid = dialect.getUndefinedSrid(); PropertyNameMapper mapper = new PropertyNameMapper() { @Override public PropertyNameMapping getMapping( ValueReference propName, TableAliasManager aliasManager ) throws FilterEvaluationException, UnmappableException { GeometryStorageParams geometryParams = new GeometryStorageParams( blobMapping.getCRS(), undefinedSrid, CoordinateDimension.DIM_2 ); GeometryMapping bboxMapping = new GeometryMapping( null, false, new DBField( blobMapping.getBBoxColumn() ), GeometryType.GEOMETRY, geometryParams, null ); return new PropertyNameMapping( getGeometryConverter( bboxMapping ), null, blobMapping.getBBoxColumn(), aliasManager.getRootTableAlias() ); } @Override public PropertyNameMapping getSpatialMapping( ValueReference propName, TableAliasManager aliasManager ) throws FilterEvaluationException, UnmappableException { return getMapping( propName, aliasManager ); } }; return dialect.getWhereBuilder( mapper, filter, null, allowInMemoryFiltering ); } public SQLDialect getDialect() { return dialect; } private class FeatureResultSetIterator extends ResultSetIterator<Feature> { private final FeatureBuilder builder; private final ResultSet rs; private final Connection conn; private final Statement stmt; public FeatureResultSetIterator( FeatureBuilder builder, ResultSet rs, Connection conn, Statement stmt ) { super( rs, conn, stmt ); this.builder = builder; this.rs = rs; this.conn = conn; this.stmt = stmt; } @Override public void close() { release( rs, stmt, conn ); } @Override protected Feature createElement( ResultSet rs ) throws SQLException { return builder.buildFeature( rs ); } } @Override public ResourceMetadata<? extends Resource> getMetadata() { return metadata; } @Override public void init() { connProvider = workspace.getResource( ConnectionProviderProvider.class, getConnId() ); LOG.debug( "init" ); List<String> resolverClasses = config.getCustomReferenceResolver(); List<GMLReferenceResolver> resolvers = new ArrayList<GMLReferenceResolver>(); for ( String resolver : resolverClasses ) { try { Class<GMLReferenceResolver> clzz = (Class<GMLReferenceResolver>) Class.forName( resolver ); Constructor<GMLReferenceResolver> cons = clzz.getConstructor( FeatureStore.class ); GMLReferenceResolver res = cons.newInstance( this ); resolvers.add( res ); LOG.info( "Added custom reference resolver {}.", clzz.getSimpleName() ); } catch ( ClassNotFoundException e ) { LOG.warn( "Custom resolver class {} could not be found on the classpath.", resolver ); LOG.trace( "Stack trace:", e ); } catch ( NoSuchMethodException e ) { LOG.warn( "Custom resolver class {} needs a constructor with a FeatureStore parameter.", resolver ); LOG.trace( "Stack trace:", e ); } catch ( SecurityException e ) { LOG.warn( "Insufficient rights to instantiate custom resolver class {}.", resolver ); LOG.trace( "Stack trace:", e ); } catch ( Throwable e ) { LOG.warn( "Could not instantiate custom resolver class {}.", resolver ); LOG.trace( "Stack trace:", e ); } } if ( !resolvers.isEmpty() ) { resolvers.add( resolver ); this.resolver = new CombinedReferenceResolver( resolvers ); } MappedAppSchema schema; try { schema = AbstractMappedSchemaBuilder.build( configURL.toString(), config, dialect, this.workspace ); } catch ( Exception t ) { throw new ResourceInitException( t.getMessage(), t ); } // lockManager = new DefaultLockManager( this, "LOCK_DB" ); this.schema = schema; this.blobMapping = schema.getBlobMapping(); initConverters(); try { // however TODO it properly on the DB ConnectionProvider conn = this.workspace.getResource( ConnectionProviderProvider.class, "LOCK_DB" ); lockManager = new DefaultLockManager( this, conn ); } catch ( Throwable e ) { LOG.warn( "Lock manager initialization failed, locking will not be available." ); LOG.trace( "Stack trace:", e ); } // TODO make this configurable FeatureStoreManager fsMgr = this.workspace.getResourceManager( FeatureStoreManager.class ); if ( fsMgr != null ) { this.bboxCache = fsMgr.getBBoxCache(); } else { LOG.warn( "Unmanaged feature store." ); } if ( config.getInspectors() != null ) { for ( CustomInspector inspectorConfig : config.getInspectors().getCustomInspector() ) { String className = inspectorConfig.getClazz(); LOG.info( "Adding custom feature inspector '" + className + "' to inspector chain." ); try { @SuppressWarnings("unchecked") Class<FeatureInspector> inspectorClass = (Class<FeatureInspector>) workspace.getModuleClassLoader().loadClass( className ); inspectors.add( inspectorClass.newInstance() ); } catch ( Exception e ) { String msg = "Unable to instantiate custom feature inspector '" + className + "': " + e.getMessage(); throw new ResourceInitException( msg ); } } } if ( config.isNullEscalation() == null ) { nullEscalation = false; } else { nullEscalation = config.isNullEscalation(); } } private void checkIfFeatureTypIsRequested( TypeName[] typeNames, FeatureType ft ) { if ( typeNames != null && typeNames.length > 0 ) { boolean isFeatureTypeRequested = false; for ( TypeName typeName : typeNames ) { if ( typeName.getFeatureTypeName().equals( ft.getName() ) ) isFeatureTypeRequested = true; } if ( !isFeatureTypeRequested ) throw new InvalidParameterValueException( "Requested feature does not match the requested feature type.", "RESOURCEID" ); } } }
package VASSAL.build; import VASSAL.build.module.Chatter; import VASSAL.build.module.PrototypeDefinition; import VASSAL.counters.Marker; import java.util.ArrayList; import java.util.HashMap; import VASSAL.build.widget.PieceSlot; import VASSAL.counters.BasicPiece; import VASSAL.counters.Decorator; import VASSAL.counters.GamePiece; import VASSAL.counters.PieceCloner; import VASSAL.counters.PlaceMarker; import VASSAL.counters.Properties; public class GpIdChecker { protected GpIdSupport gpIdSupport; protected int maxId; protected boolean useName = false; protected boolean extensionsLoaded = false; final HashMap<String, SlotElement> goodSlots = new HashMap<>(); final ArrayList<SlotElement> errorSlots = new ArrayList<>(); private Chatter chatter; public GpIdChecker() { this(null); } public GpIdChecker(GpIdSupport gpIdSupport) { this.gpIdSupport = gpIdSupport; maxId = -1; } // This constructor is used by the GameRefresher to refresh a game with extensions possibly loaded public GpIdChecker(boolean useName) { this(); this.useName = useName; this.extensionsLoaded = true; } /** * Add a PieceSlot to our cross-reference and any PlaceMarker * traits it contains. * * @param pieceSlot PieceSlot to add to cross-reference */ public void add(PieceSlot pieceSlot) { testGpId(pieceSlot.getGpId(), new SlotElement(pieceSlot)); // PlaceMarker traits within the PieceSlot definition also contain GpId's. checkTrait(pieceSlot.getPiece()); } /** * Add any PieceSlots contained in traits in a Prototype Definition * @param prototype Prototype Definition to check */ public void add(PrototypeDefinition prototype) { final GamePiece gp = prototype.getPiece(); checkTrait(gp, prototype, gp); } /** * Check for PlaceMarker traits in a GamePiece and add them to * the cross-reference * * @param gp GamePiece to check */ protected void checkTrait(GamePiece gp) { if (gp == null || gp instanceof BasicPiece) { return; } if (gp instanceof PlaceMarker) { final PlaceMarker pm = (PlaceMarker) gp; testGpId (pm.getGpId(), new SlotElement(pm)); } checkTrait(((Decorator) gp).getInner()); } protected void checkTrait(final GamePiece gp, PrototypeDefinition prototype, GamePiece definition) { if (gp == null || gp instanceof BasicPiece) { return; } if (gp instanceof PlaceMarker) { final PlaceMarker pm = (PlaceMarker) gp; testGpId (pm.getGpId(), new SlotElement(pm, prototype, definition)); } checkTrait(((Decorator) gp).getInner(), prototype, definition); } /** * Validate a GamePieceId. * - non-null * - Integer * - Not a duplicate of any other GpId * Keep a list of the good Slots and the slots with errors. * Also track the maximum GpId * * @param id GpId to test * @param element Containing SlotElement */ protected void testGpId(String id, SlotElement element) { /* * If this has been called from a ModuleExtension, the GpId is prefixed with * the Extension Id. Remove the Extension Id and just process the numeric part. * * NOTE: If GpIdChecker is being used by the GameRefesher, then there may be * extensions loaded, so retain the extension prefix to ensure a correct * unique slot id check. */ if (! extensionsLoaded) { if (id.contains(":")) { id = id.split(":")[1]; } } if (id == null || id.length() == 0) { // gpid not generated yet? errorSlots.add(element); } else { if (goodSlots.get(id) != null) { // duplicate gpid? errorSlots.add(element); } try { if (extensionsLoaded) { goodSlots.put(id, element); } else { final int iid = Integer.parseInt(id); goodSlots.put(id, element); // gpid is good. if (iid >= maxId) { maxId = iid + 1; } } } catch (Exception e) { errorSlots.add(element); // non-numeric gpid? } } } /** * Where any errors found? * @return Error count */ public boolean hasErrors() { return errorSlots.size() > 0; } private void chat (String text) { if (chatter == null) { chatter = GameModule.getGameModule().getChatter(); } final Chatter.DisplayText mess = new Chatter.DisplayText(chatter, "- " + text); mess.execute(); } /** * Repair any errors * - Update the next GpId in the module if necessary * - Generate new GpId's for slots with errors. */ public void fixErrors() { if (maxId >= gpIdSupport.getNextGpId()) { chat("Next GPID updated from " + gpIdSupport.getNextGpId() + " to " + (maxId + 1)); gpIdSupport.setNextGpId(maxId + 1); } for (SlotElement slotElement : errorSlots) { final String before = slotElement.getGpId(); slotElement.updateGpId(); chat(slotElement.toString() + " GPID updated from " + before + " to " + slotElement.getGpId()); } } /** * Locate the SlotElement that matches oldPiece and return a new GamePiece * created from that Slot. * * @param oldPiece Old GamePiece * @return Newly created GamePiece */ public GamePiece createUpdatedPiece(GamePiece oldPiece) { // Find a slot with a matching gpid final String gpid = (String) oldPiece.getProperty(Properties.PIECE_ID); if (gpid != null && gpid.length() > 0) { final SlotElement element = goodSlots.get(gpid); if (element != null) { return element.createPiece(oldPiece); } } // Failed to find a slot by gpid, try by matching piece name if option selected if (useName) { final String oldPieceName = Decorator.getInnermost(oldPiece).getName(); for (SlotElement el : goodSlots.values()) { final GamePiece newPiece = el.getPiece(); final String newPieceName = Decorator.getInnermost(newPiece).getName(); if (oldPieceName.equals(newPieceName)) { return el.createPiece(oldPiece); } } } return oldPiece; } public boolean findUpdatedPiece(GamePiece oldPiece) { // Find a slot with a matching gpid final String gpid = (String) oldPiece.getProperty(Properties.PIECE_ID); if (gpid != null && gpid.length() > 0) { final SlotElement element = goodSlots.get(gpid); if (element != null) { return true; } } // Failed to find a slot by gpid, try by matching piece name if option selected if (useName) { final String oldPieceName = Decorator.getInnermost(oldPiece).getName(); for (SlotElement el : goodSlots.values()) { final GamePiece newPiece = el.getPiece(); final String newPieceName = Decorator.getInnermost(newPiece).getName(); if (oldPieceName.equals(newPieceName)) { return true; } } } return false; } /** * Wrapper class for components that contain a GpId - They will all be either * PieceSlot components or PlaceMarker Decorator's. * PlaceMarker's may exist inside Prototypes and require special handling * Ideally we would add an interface to these components, but this * will break any custom code based on PlaceMarker * */ static class SlotElement { private PieceSlot slot; private PlaceMarker marker; private String id; private PrototypeDefinition prototype; private GamePiece expandedPrototype; public SlotElement() { slot = null; marker = null; prototype = null; expandedPrototype = null; } public SlotElement(PieceSlot ps) { this(); slot = ps; id = ps.getGpId(); } public SlotElement(PlaceMarker pm) { this(); marker = pm; id = pm.getGpId(); } public SlotElement(PlaceMarker pm, PrototypeDefinition pd, GamePiece definition) { this(); marker = pm; prototype = pd; expandedPrototype = definition; id = pm.getGpId(); } public String getGpId() { return id; } @Override public String toString() { return marker == null ? "PieceSlot " + slot.getConfigureName() : "Place/Replace trait " + marker.getDescription(); } public void updateGpId() { if (marker == null) { slot.updateGpId(); id = slot.getGpId(); } else { marker.updateGpId(); id = marker.getGpId(); // If this PlaceMarker trait lives in a Prototype, then the Prototype definition has to be updated if (prototype != null) { prototype.setPiece(expandedPrototype); } } } public GamePiece getPiece() { if (slot == null) { return marker; } else { return slot.getPiece(); } } /** * Create a new GamePiece based on this Slot Element. Use oldPiece * to copy state information over to the new piece. * * @param oldPiece Old Piece for state information * @return New Piece */ public GamePiece createPiece(GamePiece oldPiece) { GamePiece newPiece = (slot != null) ? slot.getPiece() : marker.createMarker(); // The following two steps create a complete new GamePiece with all // prototypes expanded newPiece = PieceCloner.getInstance().clonePiece(newPiece); copyState(oldPiece, newPiece); newPiece.setProperty(Properties.PIECE_ID, getGpId()); return newPiece; } /** * Copy as much state information as possible from the old * piece to the new piece * * @param oldPiece Piece to copy state from * @param newPiece Piece to copy state to */ protected void copyState(GamePiece oldPiece, GamePiece newPiece) { GamePiece p = newPiece; while (p != null) { if (p instanceof BasicPiece) { p.setState(Decorator.getInnermost(oldPiece).getState()); p = null; } else { final Decorator decorator = (Decorator) p; final String type = decorator.myGetType(); final String newState = findStateFromType(oldPiece, type, p.getClass()); // Do not copy the state of Marker traits, we want to see the new value from the new definition if (newState != null && newState.length() > 0 && !(decorator instanceof Marker)) { decorator.mySetState(newState); } p = decorator.getInner(); } } } /** * Locate a Decorator in the old piece that has the exact same * type as the new Decorator and return it's state * * @param oldPiece Old piece to search * @param typeToFind Type to match * @param classToFind Class to match * @return state of located matching Decorator */ protected String findStateFromType(GamePiece oldPiece, String typeToFind, Class<? extends GamePiece> classToFind) { GamePiece p = oldPiece; while (p != null && !(p instanceof BasicPiece)) { final Decorator d = (Decorator) Decorator.getDecorator(p, classToFind); if (d != null) { if (d.getClass().equals(classToFind)) { if (d.myGetType().equals(typeToFind)) { return d.myGetState(); } } p = d.getInner(); } else p = null; } return null; } } }
package org.geomajas.gwt.client.action.toolbar; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.geomajas.command.CommandResponse; import org.geomajas.command.dto.RefreshConfigurationRequest; import org.geomajas.command.dto.RefreshConfigurationResponse; import org.geomajas.gwt.client.action.ToolbarAction; import org.geomajas.gwt.client.command.CommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt.client.command.GwtCommandDispatcher; import org.geomajas.gwt.client.i18n.I18nProvider; import com.smartgwt.client.util.SC; import com.smartgwt.client.util.ValueCallback; import com.smartgwt.client.widgets.Dialog; import com.smartgwt.client.widgets.events.ClickEvent; /** * Reloads the server Spring configuration. * * @author Jan De Moerloose * */ public class RefreshConfigurationAction extends ToolbarAction { public RefreshConfigurationAction() { super("[ISOMORPHIC]/geomajas/reload.png", I18nProvider.getToolbar().refreshConfiguration()); } public void onClick(ClickEvent event) { Dialog d = new Dialog(); d.setWidth(400); SC.askforValue("Provide the context name", "Context file name ?", "applicationContext.xml", new ValueCallback() { public void execute(String value) { if (value != null) { RefreshConfigurationRequest request = new RefreshConfigurationRequest(); request.setConfigLocations(value.trim().split("[ \\r\\t\\n,;]+")); GwtCommand command = new GwtCommand("command.configuration.Refresh"); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new CommandCallback() { public void execute(CommandResponse response) { RefreshConfigurationResponse r = (RefreshConfigurationResponse) response; String message = "Reloaded applications : "; List<String> names = Arrays.asList(r.getApplicationNames()); for (Iterator<String> it = names.iterator(); it.hasNext();) { message += it.next(); if (it.hasNext()) { message += ","; } } SC.warn(message, null); } }); } } }, d); } }
package org.innovateuk.ifs.assessment.profile.controller; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.affiliation.service.AffiliationRestService; import org.innovateuk.ifs.assessment.resource.AssessorProfileResource; import org.innovateuk.ifs.assessment.resource.ProfileResource; import org.innovateuk.ifs.assessment.service.AssessorRestService; import org.innovateuk.ifs.category.resource.InnovationAreaResource; import org.innovateuk.ifs.populator.AssessorProfileDeclarationModelPopulator; import org.innovateuk.ifs.populator.AssessorProfileDetailsModelPopulator; import org.innovateuk.ifs.populator.AssessorProfileSkillsModelPopulator; import org.innovateuk.ifs.profile.service.ProfileRestService; import org.innovateuk.ifs.user.resource.AffiliationListResource; import org.innovateuk.ifs.user.resource.AffiliationResource; import org.innovateuk.ifs.user.resource.BusinessType; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.viewmodel.AssessorProfileDeclarationViewModel; import org.innovateuk.ifs.viewmodel.AssessorProfileDetailsViewModel; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.web.servlet.MvcResult; import java.util.List; import static java.lang.Boolean.TRUE; import static java.util.Collections.emptyList; import static org.innovateuk.ifs.assessment.builder.AssessorProfileResourceBuilder.newAssessorProfileResource; import static org.innovateuk.ifs.assessment.builder.ProfileResourceBuilder.newProfileResource; import static org.innovateuk.ifs.category.builder.InnovationAreaResourceBuilder.newInnovationAreaResource; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.user.builder.AffiliationListResourceBuilder.newAffiliationListResource; import static org.innovateuk.ifs.user.builder.AffiliationResourceBuilder.newAffiliationResource; import static org.innovateuk.ifs.user.builder.ProfileSkillsResourceBuilder.newProfileSkillsResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.AffiliationType.*; import static org.innovateuk.ifs.user.resource.BusinessType.BUSINESS; import static org.innovateuk.ifs.util.CollectionFunctions.combineLists; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; @RunWith(MockitoJUnitRunner.Silent.class) public class AssessorProfileControllerTest extends BaseControllerMockMVCTest<AssessorProfileController> { @Spy @InjectMocks private AssessorProfileSkillsModelPopulator assessorProfileSkillsModelPopulator; @Spy @InjectMocks private AssessorProfileDeclarationModelPopulator assessorProfileDeclarationModelPopulator; @Mock private AssessorProfileDetailsModelPopulator assessorProfileDetailsModelPopulator; @Mock private ProfileRestService profileRestService; @Mock private AssessorRestService assessorRestService; @Mock private AffiliationRestService affiliationRestService; @Override protected AssessorProfileController supplyControllerUnderTest() { return new AssessorProfileController( assessorProfileSkillsModelPopulator, assessorProfileDeclarationModelPopulator, profileRestService, assessorRestService ); } @Test public void getDeclaration() throws Exception { UserResource user = newUserResource().build(); BusinessType businessType = BUSINESS; ProfileResource profile = newProfileResource() .withBusinessType(businessType) .build(); setLoggedInUser(user); String expectedPrincipalEmployer = "Big Name Corporation"; String expectedRole = "Financial Accountant"; String expectedProfessionalAffiliations = "Professional affiliations..."; String expectedFinancialInterests = "Other financial interests..."; String expectedFamilyFinancialInterests = "Other family financial interests..."; List<AffiliationResource> expectedAppointments = newAffiliationResource() .withAffiliationType(PERSONAL) .withOrganisation("Org 1", "Org 2") .withPosition("Pos 1", "Post 2") .withExists(TRUE) .build(2); List<AffiliationResource> expectedFamilyAffiliations = newAffiliationResource() .withAffiliationType(FAMILY) .withRelation("Relation 1", "Relation 2") .withOrganisation("Org 1", "Org 2") .withExists(TRUE) .build(2); AffiliationResource principalEmployer = newAffiliationResource() .withAffiliationType(EMPLOYER) .withExists(TRUE) .withOrganisation(expectedPrincipalEmployer) .withPosition(expectedRole) .build(); AffiliationResource professionalAffiliations = newAffiliationResource() .withAffiliationType(PROFESSIONAL) .withExists(TRUE) .withDescription(expectedProfessionalAffiliations) .build(); AffiliationResource financialInterests = newAffiliationResource() .withAffiliationType(PERSONAL_FINANCIAL) .withExists(TRUE) .withDescription(expectedFinancialInterests) .build(); AffiliationResource familyFinancialInterests = newAffiliationResource() .withAffiliationType(FAMILY_FINANCIAL) .withExists(TRUE) .withDescription(expectedFamilyFinancialInterests) .build(); when(affiliationRestService.getUserAffiliations(user.getId())) .thenReturn(restSuccess(new AffiliationListResource(combineLists( combineLists( expectedAppointments, expectedFamilyAffiliations ), principalEmployer, professionalAffiliations, financialInterests, familyFinancialInterests ) ))); AssessorProfileDetailsViewModel assessorProfileDetailsViewModel = new AssessorProfileDetailsViewModel(user, profile); AssessorProfileResource assessorProfileResource = newAssessorProfileResource() .withUser(user) .withProfile(profile) .build(); when(assessorRestService.getAssessorProfile(anyLong())).thenReturn(restSuccess(assessorProfileResource)); when(assessorProfileDetailsModelPopulator.populateModel(user, profile)).thenReturn(assessorProfileDetailsViewModel); MvcResult result = mockMvc.perform(get("/profile/details/declaration")) .andExpect(status().isOk()) .andExpect(view().name("profile/declaration-of-interest")) .andReturn(); AssessorProfileDeclarationViewModel model = (AssessorProfileDeclarationViewModel) result.getModelAndView().getModel().get("model"); assertEquals(expectedAppointments, model.getAppointments()); assertEquals(expectedFamilyAffiliations, model.getFamilyAffiliations()); assertEquals(expectedFamilyFinancialInterests, model.getFamilyFinancialInterests()); assertEquals(expectedFinancialInterests, model.getFinancialInterests()); assertEquals(expectedPrincipalEmployer, model.getPrincipalEmployer()); assertEquals(expectedProfessionalAffiliations, model.getProfessionalAffiliations()); assertEquals(expectedRole, model.getRole()); verify(affiliationRestService).getUserAffiliations(user.getId()); } @Test public void getDeclaration_notCompleted() throws Exception { UserResource user = newUserResource().build(); BusinessType businessType = BUSINESS; ProfileResource profile = newProfileResource() .withBusinessType(businessType) .build(); setLoggedInUser(user); AssessorProfileDetailsViewModel assessorProfileDetailsViewModel = new AssessorProfileDetailsViewModel(user, profile); AffiliationListResource affiliationListResource = newAffiliationListResource() .withAffiliationList(emptyList()) .build(); AssessorProfileResource assessorProfileResource = newAssessorProfileResource() .withUser(user) .withProfile(profile) .build(); when(affiliationRestService.getUserAffiliations(user.getId())).thenReturn(restSuccess(affiliationListResource)); when(assessorRestService.getAssessorProfile(anyLong())).thenReturn(restSuccess(assessorProfileResource)); when(assessorProfileDetailsModelPopulator.populateModel(user, profile)).thenReturn(assessorProfileDetailsViewModel); MvcResult result = mockMvc.perform(get("/profile/details/declaration")) .andExpect(status().isOk()) .andExpect(view().name("profile/declaration-of-interest")) .andReturn(); AssessorProfileDeclarationViewModel model = (AssessorProfileDeclarationViewModel) result.getModelAndView().getModel().get("model"); assertEquals(emptyList(), model.getAppointments()); assertEquals(emptyList(), model.getFamilyAffiliations()); assertEquals(null, model.getFamilyFinancialInterests()); assertEquals(null, model.getFinancialInterests()); assertEquals(null, model.getPrincipalEmployer()); assertEquals(null, model.getProfessionalAffiliations()); assertEquals(null, model.getRole()); verify(affiliationRestService).getUserAffiliations(user.getId()); } private List<InnovationAreaResource> setUpInnovationAreasForSector(String sectorName, String... innovationAreaNames) { return newInnovationAreaResource() .withSectorName(sectorName) .withName(innovationAreaNames) .build(innovationAreaNames.length); } private UserResource setUpProfileSkills(BusinessType businessType, String skillAreas, List<InnovationAreaResource> innovationAreaResources) { UserResource user = newUserResource().build(); setLoggedInUser(user); when(profileRestService.getProfileSkills(user.getId())).thenReturn(restSuccess(newProfileSkillsResource() .withUser(user.getId()) .withInnovationAreas(innovationAreaResources) .withBusinessType(businessType) .withSkillsAreas(skillAreas) .build())); return user; } }
package com.dounine.japi.web; import com.dounine.japi.act.Result; import com.dounine.japi.act.ResultImpl; import com.dounine.japi.core.JapiServer; import com.dounine.japi.exception.JapiException; import com.dounine.japi.transfer.JapiNavRoot; import com.dounine.japi.transfer.JapiProject; import com.dounine.japi.web.type.FollowEnum; import com.dounine.japi.web.type.SortTypeEnum; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("project") public class ProjectAct { private static final String NOT_EMPTY_TIP = " ."; private JapiServer japiServer = new JapiServer(); private static final List<String> TIPS = new ArrayList<>(); static { TIPS.add("http."); TIPS.add("json,txt."); TIPS.add("x-www-form-urlencoded,raw,binary."); TIPS.add("rest,http://japi.dounine.com/test/{id} id."); TIPS.add(",,chrome:<a href='https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?utm_source=chrome-app-launcher-info-dialog'>postman</a>."); TIPS.add("API,JSON{code:0,msg:null,data:null},code,0,0,msg,data."); TIPS.add(",{code:0,msg:null,data:null},data."); TIPS.add(",."); TIPS.add("POST,PUT,PATCH,DELETErtoken."); TIPS.add("GET:params key:_excludes() value() name,age _excludes:name _excludes:age"); TIPS.add("GET(_includes):params key:_includes() value() name,age _includes:name _includes:age"); } private String getToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { Object tokenObject = httpServletRequest.getHeader("token"); if (null == tokenObject) { tokenObject = httpServletRequest.getParameter("token"); } if (null == tokenObject) { throw new JapiException("token"); } return tokenObject.toString(); } @GetMapping("tip") public Result tip(){ ResultImpl result = new ResultImpl(); result.setData(TIPS); return result; } @PostMapping("follow") public Result followAdd(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String projectName) throws JapiException { String token = getToken(httpServletRequest, httpServletResponse); ResultImpl result = new ResultImpl(); if (StringUtils.isBlank(projectName)) { throw new JapiException("projectName" + NOT_EMPTY_TIP); } japiServer.follow(token, projectName, FollowEnum.ADD); result.setMsg("success"); return result; } @PostMapping("delFollow") public Result followDel(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String projectName) throws JapiException { String token = getToken(httpServletRequest, httpServletResponse); ResultImpl result = new ResultImpl(); if (StringUtils.isBlank(projectName)) { throw new JapiException("projectName" + NOT_EMPTY_TIP); } japiServer.follow(token, projectName, FollowEnum.DEL); result.setMsg("success"); return result; } @PostMapping("navs") public Result navs(String projectName) throws JapiException { if (StringUtils.isBlank(projectName)) { throw new JapiException("projectName" + NOT_EMPTY_TIP); } ResultImpl<JapiNavRoot> rest = new ResultImpl<JapiNavRoot>(); rest.setData(japiServer.getProjectNav(projectName)); return rest; } @GetMapping("{projectName}/logo") public void logo(HttpServletResponse response, @PathVariable String projectName) throws JapiException { response.setHeader("Content-Type", "image/png"); InputStream fis = japiServer.getIconInputStream(projectName); OutputStream os = null; try { os = response.getOutputStream(); byte[] bytes = new byte[1024]; int len = -1; while ((len = fis.read(bytes)) != -1) { os.write(bytes, 0, len); } os.flush(); fis.close(); } catch (IOException e) { throw new JapiException(e.getMessage()); } } @PostMapping("versions") public Result versions(TransferInfo transferInfo) throws JapiException { if (StringUtils.isBlank(transferInfo.getProjectName())) { throw new JapiException("projectName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getPackageName())) { throw new JapiException("packageName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getFunName())) { throw new JapiException("funName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getActionName())) { throw new JapiException("actionName" + NOT_EMPTY_TIP); } ResultImpl rest = new ResultImpl(); List<String> versions = japiServer.getActionVersions(transferInfo); versions.sort((b, a) -> { return new Integer(Integer.parseInt(a.substring(1))).compareTo(Integer.parseInt(b.substring(1))); }); rest.setData(versions); return rest; } @PostMapping("dates") public Result dates(TransferInfo transferInfo) throws JapiException { if (StringUtils.isBlank(transferInfo.getProjectName())) { throw new JapiException("projectName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getPackageName())) { throw new JapiException("packageName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getFunName())) { throw new JapiException("funName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getActionName())) { throw new JapiException("actionName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getVersionName())) { throw new JapiException("versionName" + NOT_EMPTY_TIP); } ResultImpl rest = new ResultImpl(); List<String> datas = japiServer.getActionVerDates(transferInfo); datas.sort((b, a) -> a.compareTo(b)); rest.setData(datas); return rest; } @PostMapping("action") public void action(HttpServletResponse response, TransferInfo transferInfo) throws JapiException { response.setHeader("Content-Type", "application/json;charset=UTF-8"); if (StringUtils.isBlank(transferInfo.getProjectName())) { throw new JapiException("projectName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getPackageName())) { throw new JapiException("packageName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getFunName())) { throw new JapiException("funName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getActionName())) { throw new JapiException("actionName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getVersionName())) { throw new JapiException("versionName" + NOT_EMPTY_TIP); } if (StringUtils.isBlank(transferInfo.getDateName())) { throw new JapiException("dateName" + NOT_EMPTY_TIP); } try { response.getWriter().print("{\"code\":0,\"msg\":null,\"data\":" + japiServer.getAction(transferInfo) + "}"); } catch (IOException e) { throw new JapiException(e.getMessage()); } } @GetMapping("count") public Result count() throws JapiException { ResultImpl rest = new ResultImpl(); rest.setData(japiServer.getAllProjects().size()); return rest; } @GetMapping("lists/{offset}/{limit}") public Result lists(@PathVariable Integer offset, @PathVariable Integer limit, String sortName, SortTypeEnum sortType, HttpServletRequest request, HttpServletResponse response) throws JapiException { if (offset <= 0) { offset = 1; } if (limit <= 0) { limit = 8; } List<JapiProject> projects = japiServer.getAllProjects(); if (StringUtils.isNotBlank(sortName)) { if ("createTime".equals(sortName)) { if (null == sortType || (null != sortType && sortType.equals(SortTypeEnum.ASC))) { projects.sort((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())); } else { projects.sort((b, a) -> a.getCreateTime().compareTo(b.getCreateTime())); } } else if ("author".equals(sortName)) { if (null == sortType || (null != sortType && sortType.equals(SortTypeEnum.ASC))) { projects.sort((a, b) -> a.getAuthor().compareTo(b.getAuthor())); } else { projects.sort((b, a) -> a.getAuthor().compareTo(b.getAuthor())); } } else if ("name".equals(sortName)) { if (null == sortType || (null != sortType && sortType.equals(SortTypeEnum.ASC))) { projects.sort((a, b) -> a.getName().compareTo(b.getName())); } else { projects.sort((b, a) -> a.getName().compareTo(b.getName())); } } } ResultImpl rest = new ResultImpl(); int beginIndex = limit * (offset - 1); if (beginIndex > projects.size()) { beginIndex = 0; } int endIndex = beginIndex + limit; if (endIndex > projects.size()) { endIndex = projects.size(); } List<JapiProject> japiProjects = projects.subList(beginIndex, endIndex); String token = getToken(request, response); List<String> projectNames = japiServer.getFollows(token); for (String projectName : projectNames) { final String _projectName = projectName; japiProjects.forEach(jp -> { if (jp.getName().equals(_projectName)) { jp.setFollow(true); } }); } rest.setData(japiProjects); return rest; } }
package org.safehaus.kiskis.mgmt.api.commandrunner; import com.google.common.base.Preconditions; import org.safehaus.kiskis.mgmt.shared.protocol.Agent; import java.util.Set; /** * This class is used to hold commands specific to client. * One needs to call {@code init} method prior to using it. * Clients should extend this class and add custom commands creation methods * e.g. * <p/> * <blockquote><pre> * public class Commands extends CommandsSingleton{ * public static Command getStartCommand(Set<Agent> agents) { * return createCommand( * new RequestBuilder("service solr start").withTimeout(60), * agents); * } * } * </pre></blockquote> * <p/> * Then somewhere in client code prior to using this class: * <p/> * {@code Commands.init(commandRunnner);} * * @author dilshat */ public class CommandsSingleton { private static CommandsSingleton INSTANCE = new CommandsSingleton(); private CommandRunner commandRunner; protected CommandsSingleton() { } public final static void init(CommandRunner commandRunner) { Preconditions.checkNotNull(commandRunner, "Command Runner is null"); INSTANCE.commandRunner = commandRunner; } protected static Command createCommand(RequestBuilder requestBuilder, Set<Agent> agents) { return INSTANCE.commandRunner.createCommand(requestBuilder, agents); } protected static Command createCommand(Set<AgentRequestBuilder> agentRequestBuilders) { return INSTANCE.commandRunner.createCommand(agentRequestBuilders); } }
package io.vivarium.util; import java.io.Serializable; import com.google.common.io.BaseEncoding; import com.google.common.primitives.Longs; import com.googlecode.gwtstreamer.client.Streamable; /** * Guava based UUID implementation for compatibility with GWT. This class can be used as a plug in replacement for the * standard java.util.UUID, but it's worth noting that GWT does not support SecureRandom, so this UUID implementation * does not provide the same guarantee of entropy. It's much preferable to generate UUIDs from the java.util.UUID and * convert into this class before sending to GWT if possible. * * @author John H. Uckele */ public class UUID implements Serializable, Streamable { private static final long serialVersionUID = -3965221404087809719L; private static final BaseEncoding ENCODING = BaseEncoding.base16().lowerCase(); private long _long1; private long _long2; private UUID() { } public static UUID randomUUID() { UUID uuid = new UUID(); // This is compatible with a real UUID, but it is not cryptographically secure. uuid._long1 = Rand.getInstance().getRandomLong(); uuid._long2 = Rand.getInstance().getRandomLong2(); return uuid; } @Override public String toString() { StringBuilder sb = new StringBuilder(); // encode first long byte[] bytes1 = Longs.toByteArray(_long1); sb.append(ENCODING.encode(bytes1, 0, 4)).append('-'); sb.append(ENCODING.encode(bytes1, 4, 2)).append('-'); sb.append(ENCODING.encode(bytes1, 6, 2)).append('-'); // encode second long byte[] bytes2 = Longs.toByteArray(_long2); sb.append(ENCODING.encode(bytes2, 0, 2)).append('-'); sb.append(ENCODING.encode(bytes2, 2, 6)); return sb.toString(); } public static UUID fromString(String s) { UUID uuid = new UUID(); s = s.replaceAll("-", "").toLowerCase(); // decode first long byte[] bytes1 = ENCODING.decode(s.substring(0, 16)); uuid._long1 = Longs.fromByteArray(bytes1); // decode second long byte[] bytes2 = ENCODING.decode(s.substring(16, 32)); uuid._long2 = Longs.fromByteArray(bytes2); return uuid; } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object that) { return this.toString().equals(String.valueOf(that)); } }
package com.sun.star.comp.helper; /** * BootstrapException is a checked exception that wraps an exception * thrown by the original target. * * @since UDK 3.1.0 */ public class BootstrapException extends java.lang.Exception { /** * This field holds the target exception. */ private Exception m_target = null; /** * Constructs a <code>BootstrapException</code> with <code>null</code> as * the target exception. */ public BootstrapException() { super(); } /** * Constructs a <code>BootstrapException</code> with the specified * detail message. * * @param message the detail message */ public BootstrapException( String message ) { super( message ); } /** * Constructs a <code>BootstrapException</code> with the specified * detail message and a target exception. * * @param message the detail message * @param target the target exception */ public BootstrapException( String message, Exception target ) { super( message ); m_target = target; } /** * Constructs a <code>BootstrapException</code> with a target exception. * * @param target the target exception */ public BootstrapException( Exception target ) { super(); m_target = target; } /** * Get the thrown target exception. * * @return the target exception */ public Exception getTargetException() { return m_target; } }
package com.jme3.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; /** * This class contains the reflection based way to remove DirectByteBuffers in * java, allocation is done via ByteBuffer.allocateDirect */ public final class ReflectionAllocator implements BufferAllocator { private static Method cleanerMethod = null; private static Method cleanMethod = null; private static Method viewedBufferMethod = null; private static Method freeMethod = null; static { // Oracle JRE / OpenJDK cleanerMethod = loadMethod("sun.nio.ch.DirectBuffer", "cleaner"); cleanMethod = loadMethod("sun.misc.Cleaner", "clean"); viewedBufferMethod = loadMethod("sun.nio.ch.DirectBuffer", "viewedBuffer"); if (viewedBufferMethod == null) { // They changed the name in Java 7 viewedBufferMethod = loadMethod("sun.nio.ch.DirectBuffer", "attachment"); } // Apache Harmony (allocated directly, to not trigger allocator used // logic in BufferUtils) ByteBuffer bb = ByteBuffer.allocateDirect(1); Class<?> clazz = bb.getClass(); try { freeMethod = clazz.getMethod("free"); } catch (NoSuchMethodException ex) { } catch (SecurityException ex) { } } private static Method loadMethod(String className, String methodName) { try { Method method = Class.forName(className).getMethod(methodName); method.setAccessible(true);// according to the Java documentation, by default, a reflected object is not accessible return method; } catch (NoSuchMethodException ex) { return null; // the method was not found } catch (SecurityException ex) { return null; // setAccessible not allowed by security policy } catch (ClassNotFoundException ex) { return null; // the direct buffer implementation was not found } catch (Throwable t) { if (t.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) { return null;// the class is in an unexported module } else { throw t; } } } @Override /** * This function explicitly calls the Cleaner method of a direct buffer. * * @param toBeDestroyed * The direct buffer that will be "cleaned". Utilizes reflection. * */ public void destroyDirectBuffer(Buffer toBeDestroyed) { try { if (freeMethod != null) { freeMethod.invoke(toBeDestroyed); } else { //TODO load the methods only once, store them into a cache (only for Java >= 9) Method localCleanerMethod; if (cleanerMethod == null) { localCleanerMethod = loadMethod(toBeDestroyed.getClass().getName(), "cleaner"); } else { localCleanerMethod = cleanerMethod; } if (localCleanerMethod == null) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "Buffer cannot be destroyed: {0}", toBeDestroyed); } else { Object cleaner = localCleanerMethod.invoke(toBeDestroyed); if (cleaner != null) { Method localCleanMethod; if (cleanMethod == null) { if (cleaner instanceof Runnable) { // jdk.internal.ref.Cleaner implements Runnable in Java 9 localCleanMethod = loadMethod(Runnable.class.getName(), "run"); } else { // sun.misc.Cleaner does not implement Runnable in Java < 9 localCleanMethod = loadMethod(cleaner.getClass().getName(), "clean"); } } else { localCleanMethod = cleanMethod; } if (localCleanMethod == null) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "Buffer cannot be destroyed: {0}", toBeDestroyed); } else { localCleanMethod.invoke(cleaner); } } else { Method localViewedBufferMethod; if (viewedBufferMethod == null) { localViewedBufferMethod = loadMethod(toBeDestroyed.getClass().getName(), "viewedBuffer"); } else { localViewedBufferMethod = viewedBufferMethod; } if (localViewedBufferMethod == null) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "Buffer cannot be destroyed: {0}", toBeDestroyed); } else { // Try the alternate approach of getting the viewed // buffer // first Object viewedBuffer = localViewedBufferMethod.invoke(toBeDestroyed); if (viewedBuffer != null) { if (viewedBuffer instanceof Buffer) { destroyDirectBuffer((Buffer) viewedBuffer); } else { //on android there is an internal MemoryRef class that is returned and has a "free" method. Method freeMethod = loadMethod(viewedBuffer.getClass().getName(), "free"); if (freeMethod != null) { freeMethod.invoke(viewedBuffer); } else { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "Buffer cannot be destroyed: {0}, {1}", new Object[]{toBeDestroyed, viewedBuffer}); } } } else { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "Buffer cannot be destroyed: {0}", toBeDestroyed); } } } } } } catch (IllegalAccessException ex) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex); } catch (IllegalArgumentException ex) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex); } catch (InvocationTargetException ex) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex); } catch (SecurityException ex) { Logger.getLogger(BufferUtils.class.getName()).log(Level.SEVERE, "{0}", ex); } } @Override public ByteBuffer allocate(int size) { return ByteBuffer.allocateDirect(size); } }
package com.fsck.k9.view; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.List; import android.annotation.SuppressLint; import android.app.Activity; import android.app.LoaderManager; import android.app.LoaderManager.LoaderCallbacks; import android.content.Context; import android.content.Loader; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract.Contacts; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.Editable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.ListPopupWindow; import android.widget.ListView; import android.widget.TextView; import com.fsck.k9.K9; import com.fsck.k9.R; import com.fsck.k9.activity.AlternateRecipientAdapter; import com.fsck.k9.activity.AlternateRecipientAdapter.AlternateRecipientListener; import com.fsck.k9.activity.RecipientAdapter; import com.fsck.k9.activity.RecipientLoader; import com.fsck.k9.mail.Address; import com.fsck.k9.view.RecipientSelectView.Recipient; import com.tokenautocomplete.TokenCompleteTextView; public class RecipientSelectView extends TokenCompleteTextView<Recipient> implements LoaderCallbacks<List<Recipient>>, AlternateRecipientListener { private static final int MINIMUM_LENGTH_FOR_FILTERING = 2; private static final String ARG_QUERY = "query"; private static final int LOADER_ID_FILTERING = 0; private static final int LOADER_ID_ALTERNATES = 1; private RecipientAdapter adapter; private String cryptoProvider; private LoaderManager loaderManager; private ListPopupWindow alternatesPopup; private AlternateRecipientAdapter alternatesAdapter; private Recipient alternatesPopupRecipient; private boolean attachedToWindow = true; private TokenListener<Recipient> listener; public RecipientSelectView(Context context) { super(context); initView(context); } public RecipientSelectView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public RecipientSelectView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); } private void initView(Context context) { // TODO: validator? alternatesPopup = new ListPopupWindow(context); alternatesAdapter = new AlternateRecipientAdapter(context, this); alternatesPopup.setAdapter(alternatesAdapter); // don't allow duplicates, based on equality of recipient objects, which is e-mail addresses allowDuplicates(false); // if a token is completed, pick an entry based on best guess. // Note that we override performCompletion, so this doesn't actually do anything performBestGuess(true); adapter = new RecipientAdapter(context); setAdapter(adapter); } @Override protected View getViewForObject(Recipient recipient) { View view = inflateLayout(); RecipientTokenViewHolder holder = new RecipientTokenViewHolder(view); view.setTag(holder); bindObjectView(recipient, view); return view; } @SuppressLint("InflateParams") private View inflateLayout() { LayoutInflater layoutInflater = LayoutInflater.from(getContext()); return layoutInflater.inflate(R.layout.recipient_token_item, null, false); } private void bindObjectView(Recipient recipient, View view) { RecipientTokenViewHolder holder = (RecipientTokenViewHolder) view.getTag(); holder.vName.setText(recipient.getDisplayNameOrAddress()); RecipientAdapter.setContactPhotoOrPlaceholder(getContext(), holder.vContactPhoto, recipient); boolean hasCryptoProvider = cryptoProvider != null; if (!hasCryptoProvider) { holder.cryptoStatusRed.setVisibility(View.GONE); holder.cryptoStatusOrange.setVisibility(View.GONE); holder.cryptoStatusGreen.setVisibility(View.GONE); } else if (recipient.cryptoStatus == RecipientCryptoStatus.UNAVAILABLE) { holder.cryptoStatusRed.setVisibility(View.VISIBLE); holder.cryptoStatusOrange.setVisibility(View.GONE); holder.cryptoStatusGreen.setVisibility(View.GONE); } else if (recipient.cryptoStatus == RecipientCryptoStatus.AVAILABLE_UNTRUSTED) { holder.cryptoStatusRed.setVisibility(View.GONE); holder.cryptoStatusOrange.setVisibility(View.VISIBLE); holder.cryptoStatusGreen.setVisibility(View.GONE); } else if (recipient.cryptoStatus == RecipientCryptoStatus.AVAILABLE_TRUSTED) { holder.cryptoStatusRed.setVisibility(View.GONE); holder.cryptoStatusOrange.setVisibility(View.GONE); holder.cryptoStatusGreen.setVisibility(View.VISIBLE); } } @Override public boolean onTouchEvent(@NonNull MotionEvent event) { int action = event.getActionMasked(); Editable text = getText(); if (text != null && action == MotionEvent.ACTION_UP) { int offset = getOffsetForPosition(event.getX(), event.getY()); if (offset != -1) { TokenImageSpan[] links = text.getSpans(offset, offset, RecipientTokenSpan.class); if (links.length > 0) { showAlternates(links[0].getToken()); return true; } } } return super.onTouchEvent(event); } @Override protected Recipient defaultObject(String completionText) { Address[] parsedAddresses = Address.parse(completionText); if (parsedAddresses.length == 0 || parsedAddresses[0].getAddress() == null) { return null; } return new Recipient(parsedAddresses[0]); } public boolean isEmpty() { return getObjects().isEmpty(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); attachedToWindow = true; if (getContext() instanceof Activity) { Activity activity = (Activity) getContext(); loaderManager = activity.getLoaderManager(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); attachedToWindow = false; } @Override public void showDropDown() { boolean cursorIsValid = adapter != null; if (!cursorIsValid) { return; } super.showDropDown(); } @Override public void performCompletion() { if (getListSelection() == ListView.INVALID_POSITION && enoughToFilter()) { Object bestGuess; if (getAdapter().getCount() > 0) { bestGuess = getAdapter().getItem(0); } else { bestGuess = defaultObject(currentCompletionText()); } if (bestGuess != null) { replaceText(convertSelectionToString(bestGuess)); } } else { super.performCompletion(); } } @Override protected void performFiltering(@NonNull CharSequence text, int start, int end, int keyCode) { String query = text.subSequence(start, end).toString(); if (TextUtils.isEmpty(query) || query.length() < MINIMUM_LENGTH_FOR_FILTERING) { loaderManager.destroyLoader(LOADER_ID_FILTERING); return; } Bundle args = new Bundle(); args.putString(ARG_QUERY, query); loaderManager.restartLoader(LOADER_ID_FILTERING, args, this); } public void setCryptoProvider(String cryptoProvider) { this.cryptoProvider = cryptoProvider; } public void addRecipients(Recipient... recipients) { for (Recipient recipient : recipients) { addObject(recipient); } } public Address[] getAddresses() { List<Recipient> recipients = getObjects(); Address[] address = new Address[recipients.size()]; for (int i = 0; i < address.length; i++) { address[i] = recipients.get(i).address; } return address; } private void showAlternates(Recipient recipient) { if (!attachedToWindow) { return; } InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getWindowToken(), 0); alternatesPopupRecipient = recipient; loaderManager.restartLoader(LOADER_ID_ALTERNATES, null, RecipientSelectView.this); } public void postShowAlternatesPopup(final List<Recipient> data) { // We delay this call so the soft keyboard is gone by the time the popup is layouted new Handler().post(new Runnable() { @Override public void run() { showAlternatesPopup(data); } }); } public void showAlternatesPopup(List<Recipient> data) { if (!attachedToWindow) { return; } // Copy anchor settings from the autocomplete dropdown View anchorView = getRootView().findViewById(getDropDownAnchor()); alternatesPopup.setAnchorView(anchorView); alternatesPopup.setWidth(getDropDownWidth()); alternatesAdapter.setCurrentRecipient(alternatesPopupRecipient); alternatesAdapter.setAlternateRecipientInfo(data); // Clear the checked item. alternatesPopup.show(); ListView listView = alternatesPopup.getListView(); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } @Override public Loader<List<Recipient>> onCreateLoader(int id, Bundle args) { switch (id) { case LOADER_ID_FILTERING: { String query = args != null && args.containsKey(ARG_QUERY) ? args.getString(ARG_QUERY) : ""; adapter.setHighlight(query); return new RecipientLoader(getContext(), cryptoProvider, query); } case LOADER_ID_ALTERNATES: { Uri contactLookupUri = alternatesPopupRecipient.getContactLookupUri(); if (contactLookupUri != null) { return new RecipientLoader(getContext(), cryptoProvider, contactLookupUri, true); } else { String address = alternatesPopupRecipient.address.getAddress(); return new RecipientLoader(getContext(), cryptoProvider, address); } } } throw new IllegalStateException("Unknown Loader ID: " + id); } @Override public void onLoadFinished(Loader<List<Recipient>> loader, List<Recipient> data) { switch (loader.getId()) { case LOADER_ID_FILTERING: { adapter.setRecipients(data); break; } case LOADER_ID_ALTERNATES: { postShowAlternatesPopup(data); loaderManager.destroyLoader(LOADER_ID_ALTERNATES); break; } } } @Override public void onLoaderReset(Loader<List<Recipient>> loader) { if (loader.getId() == LOADER_ID_FILTERING) { adapter.setHighlight(null); adapter.setRecipients(null); } } public boolean hasUncompletedText() { return !TextUtils.isEmpty(currentCompletionText()); } @Override public void onRecipientRemove(Recipient currentRecipient) { alternatesPopup.dismiss(); removeObject(currentRecipient); } @Override public void onRecipientChange(Recipient currentRecipient, Recipient alternateAddress) { alternatesPopup.dismiss(); currentRecipient.address = alternateAddress.address; currentRecipient.addressLabel = alternateAddress.addressLabel; currentRecipient.cryptoStatus = alternateAddress.cryptoStatus; View recipientTokenView = getTokenViewForRecipient(currentRecipient); if (recipientTokenView == null) { Log.e(K9.LOG_TAG, "Tried to refresh invalid view token!"); return; } bindObjectView(currentRecipient, recipientTokenView); if (listener != null) { listener.onTokenChanged(currentRecipient); } invalidate(); } /** * This method builds the span given a recipient object. We override it with identical * functionality, but using the custom RecipientTokenSpan class which allows us to * retrieve the view for redrawing at a later point. */ @Override protected TokenImageSpan buildSpanForObject(Recipient obj) { if (obj == null) { return null; } View tokenView = getViewForObject(obj); return new RecipientTokenSpan(tokenView, obj, (int) maxTextWidth()); } private View getTokenViewForRecipient(Recipient currentRecipient) { Editable text = getText(); if (text == null) { return null; } RecipientTokenSpan[] recipientSpans = text.getSpans(0, text.length(), RecipientTokenSpan.class); for (RecipientTokenSpan recipientSpan : recipientSpans) { if (recipientSpan.getToken() == currentRecipient) { return recipientSpan.view; } } return null; } /** * We use a specialized version of TokenCompleteTextView.TokenListener as well, * adding a callback for onTokenChanged. */ public void setTokenListener(TokenListener<Recipient> listener) { super.setTokenListener(listener); this.listener = listener; } public enum RecipientCryptoStatus { UNDEFINED, UNAVAILABLE, AVAILABLE_UNTRUSTED, AVAILABLE_TRUSTED; public boolean isAvailable() { return this == AVAILABLE_TRUSTED || this == AVAILABLE_UNTRUSTED; } } public interface TokenListener<T> extends TokenCompleteTextView.TokenListener<T> { void onTokenChanged(T token); } private class RecipientTokenSpan extends TokenImageSpan { private final View view; public RecipientTokenSpan(View view, Recipient recipient, int token) { super(view, recipient, token); this.view = view; } } private static class RecipientTokenViewHolder { public final TextView vName; public final ImageView vContactPhoto; public final View cryptoStatusRed; public final View cryptoStatusOrange; public final View cryptoStatusGreen; RecipientTokenViewHolder(View view) { vName = (TextView) view.findViewById(android.R.id.text1); vContactPhoto = (ImageView) view.findViewById(R.id.contact_photo); cryptoStatusRed = view.findViewById(R.id.contact_crypto_status_red); cryptoStatusOrange = view.findViewById(R.id.contact_crypto_status_orange); cryptoStatusGreen = view.findViewById(R.id.contact_crypto_status_green); } } public static class Recipient implements Serializable { @Nullable // null means the address is not associated with a contact public final Long contactId; public final String contactLookupKey; @NonNull public Address address; public String addressLabel; @Nullable // null if the contact has no photo. transient because we serialize this manually, see below. public transient Uri photoThumbnailUri; @NonNull private RecipientCryptoStatus cryptoStatus; public Recipient(@NonNull Address address) { this.address = address; this.contactId = null; this.cryptoStatus = RecipientCryptoStatus.UNDEFINED; this.contactLookupKey = null; } public Recipient(String name, String email, String addressLabel, long contactId, String lookupKey) { this.address = new Address(email, name); this.contactId = contactId; this.addressLabel = addressLabel; this.cryptoStatus = RecipientCryptoStatus.UNDEFINED; this.contactLookupKey = lookupKey; } public String getDisplayNameOrAddress() { String displayName = getDisplayName(); if (displayName != null) { return displayName; } return address.getAddress(); } public String getDisplayNameOrUnknown(Context context) { String displayName = getDisplayName(); if (displayName != null) { return displayName; } return context.getString(R.string.unknown_recipient); } private String getDisplayName() { if (TextUtils.isEmpty(address.getPersonal())) { return null; } String displayName = address.getPersonal(); if (addressLabel != null) { displayName += " (" + addressLabel + ")"; } return displayName; } @NonNull public RecipientCryptoStatus getCryptoStatus() { return cryptoStatus; } public void setCryptoStatus(@NonNull RecipientCryptoStatus cryptoStatus) { this.cryptoStatus = cryptoStatus; } @Nullable public Uri getContactLookupUri() { if (contactId == null) { return null; } return Contacts.getLookupUri(contactId, contactLookupKey); } @Override public boolean equals(Object o) { // Equality is entirely up to the address return o instanceof Recipient && address.equals(((Recipient) o).address); } private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); // custom serialization, Android's Uri class is not serializable if (photoThumbnailUri != null) { oos.writeInt(1); oos.writeUTF(photoThumbnailUri.toString()); } else { oos.writeInt(0); } } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); // custom deserialization, Android's Uri class is not serializable if (ois.readInt() != 0) { String uriString = ois.readUTF(); photoThumbnailUri = Uri.parse(uriString); } } } }
package com.ge.research.sadl.externalmodels.editors; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Properties; import java.util.StringTokenizer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.editors.text.TextEditor; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.MultiPageEditorPart; /** * An example showing how to create a multi-page editor. * This example has 3 pages: * <ul> * <li>page 0 contains a nested text editor. * <li>page 1 allows you to change the font used in page 2 * <li>page 2 shows the words in page 0 in sorted order * </ul> */ public class UrlListEditor extends MultiPageEditorPart implements IResourceChangeListener{ /** The text editor used in page 0. */ private TextEditor editor; /** * Creates a multi-page editor example. */ public UrlListEditor() { super(); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } /** * Creates page 0 of the multi-page editor, * which contains a text editor. */ void createPage0() { try { editor = new TextEditor(); int index = addPage(editor, getEditorInput()); setPageText(index, editor.getTitle()); } catch (PartInitException e) { ErrorDialog.openError( getSite().getShell(), "Error creating nested text editor", null, e.getStatus()); } } /** * Creates page 1 of the multi-page editor, * which allows you to change the font used in page 2. */ void createPage1() { Composite composite = new Composite(getContainer(), SWT.NONE); GridLayout layout = new GridLayout(); composite.setLayout(layout); layout.numColumns = 2; Button downloadButton = new Button(composite, SWT.NONE); GridData gd = new GridData(GridData.BEGINNING); gd.horizontalSpan = 2; downloadButton.setLayoutData(gd); downloadButton.setText("Download External Models"); downloadButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { downloadModels(); } }); int index = addPage(composite); setPageText(index, "Download"); } /** * Creates the pages of the multi-page editor. */ protected void createPages() { createPage0(); createPage1(); } /** * The <code>MultiPageEditorPart</code> implementation of this * <code>IWorkbenchPart</code> method disposes all nested editors. * Subclasses may extend. */ public void dispose() { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); super.dispose(); } /** * Saves the multi-page editor's document. */ public void doSave(IProgressMonitor monitor) { getEditor(0).doSave(monitor); } /** * Saves the multi-page editor's document as another file. * Also updates the text for page 0's tab, and updates this multi-page editor's input * to correspond to the nested editor's. */ public void doSaveAs() { IEditorPart editor = getEditor(0); editor.doSaveAs(); setPageText(0, editor.getTitle()); setInput(editor.getEditorInput()); } /* (non-Javadoc) * Method declared on IEditorPart */ public void gotoMarker(IMarker marker) { setActivePage(0); IDE.gotoMarker(getEditor(0), marker); } /** * The <code>MultiPageEditorExample</code> implementation of this method * checks that the input is an instance of <code>IFileEditorInput</code>. */ public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException { if (!(editorInput instanceof IFileEditorInput)) throw new PartInitException("Invalid Input: Must be IFileEditorInput"); super.init(site, editorInput); } /* (non-Javadoc) * Method declared on IEditorPart. */ public boolean isSaveAsAllowed() { return true; } /** * Closes all project files on project close. */ public void resourceChanged(final IResourceChangeEvent event){ if(event.getType() == IResourceChangeEvent.PRE_CLOSE){ Display.getDefault().asyncExec(new Runnable(){ public void run(){ IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages(); for (int i = 0; i<pages.length; i++){ if(((FileEditorInput)editor.getEditorInput()).getFile().getProject().equals(event.getResource())){ IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput()); pages[i].closeEditor(editorPart,true); } } } }); } } /** * Downloads the files to the local folder. */ void downloadModels() { String editorText = editor.getDocumentProvider().getDocument(editor.getEditorInput()).get(); StringTokenizer tokenizer = new StringTokenizer(editorText, "\n\r"); ArrayList<String> urls = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { urls.add(tokenizer.nextToken()); } IFile editorFile = ((FileEditorInput) editor.getEditorInput()).getFile(); IPath outputPath = (editorFile.getParent().getLocation()) .append(editorFile.getName().substring(0, editorFile.getName().lastIndexOf("."))); for (int i = 0; i < urls.size(); i++) { downloadURL((String) urls.get(i), outputPath); } try { ((FileEditorInput) editor.getEditorInput()).getFile().getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void downloadURL(String urlString, IPath iPath) { URL url; InputStream is = null; try { Properties p = System.getProperties(); p.put("http.proxyHost", "http-proxy.ae.ge.com"); p.put("http.proxyPort", "80"); p.put("https.proxyHost", "http-proxy.ae.ge.com"); p.put("https.proxyPort", "80"); System.setProperties(p); url = new URL(urlString); is = url.openStream(); // throws an IOException ReadableByteChannel rbc = Channels.newChannel(is); String urlPath = url.getHost() + url.getPath(); if (url.getPath() == null || url.getPath().isEmpty()) urlPath = urlPath + "/" + url.getHost() + ".owl"; else if (!url.getPath().contains(".")) urlPath = urlPath + "/" + urlPath.substring(urlPath.lastIndexOf("/")+1) + ".owl"; String outputPath = iPath.append(urlPath).toString(); File file1 = new File(outputPath.substring(0, outputPath.lastIndexOf("/"))); file1.mkdirs(); FileOutputStream fos = new FileOutputStream(outputPath); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { // nothing to see here } } } }
package org.jboss.as.web; import org.apache.catalina.InstanceEvent; import org.apache.catalina.InstanceListener; import org.jboss.as.ee.naming.NamespaceSelectorService; /** * An InstanceListener used to push/pop the application naming context. * * @author Stuart Douglas */ public class NamingListener implements InstanceListener { private final NamespaceSelectorService selector; /** * Thread local used to initialise the Listener after startup. * * TODO: figure out a better way to do this */ private static final ThreadLocal<NamespaceSelectorService> localSelector = new ThreadLocal<NamespaceSelectorService>(); public NamingListener() { selector = localSelector.get(); assert selector != null : "selector is null"; } public void instanceEvent(InstanceEvent event) { String type = event.getType(); // Push the identity on the before init/destroy if (type.equals(InstanceEvent.BEFORE_DISPATCH_EVENT) || type.equals(InstanceEvent.BEFORE_REQUEST_EVENT) || type.equals(InstanceEvent.BEFORE_DESTROY_EVENT) || type.equals(InstanceEvent.BEFORE_INIT_EVENT)) { // Push naming id selector.activate(); } // Pop the identity on the after init/destroy else if (type.equals(InstanceEvent.AFTER_DISPATCH_EVENT) || type.equals(InstanceEvent.AFTER_REQUEST_EVENT) || type.equals(InstanceEvent.AFTER_DESTROY_EVENT) || type.equals(InstanceEvent.AFTER_INIT_EVENT)) { // Pop naming id selector.deactivate(); } } public static void beginComponentStart(NamespaceSelectorService selector) { localSelector.set(selector); selector.activate(); } public static void endComponentStart() { localSelector.get().deactivate(); localSelector.set(null); } }
package net.hillsdon.reviki.wiki.renderer.creole; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.TerminalNode; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.uwyn.jhighlight.renderer.XhtmlRendererFactory; import net.hillsdon.reviki.vc.AttachmentHistory; import net.hillsdon.reviki.vc.PageInfo; import net.hillsdon.reviki.vc.PageStore; import net.hillsdon.reviki.vc.PageStoreException; import net.hillsdon.reviki.web.urls.URLOutputFilter; import net.hillsdon.reviki.wiki.renderer.creole.Creole.*; import net.hillsdon.reviki.wiki.renderer.creole.ast.*; import net.hillsdon.reviki.wiki.renderer.creole.links.LinkPartsHandler; /** * Helper class providing some useful functions for walking through the Creole * parse tree and building an AST. * * @author msw */ public abstract class CreoleASTBuilder extends CreoleBaseVisitor<ASTNode> { /** The page store. */ private final Optional<PageStore> _store; /** The page being rendered. */ private final PageInfo _page; /** The URL handler for links. */ private final LinkPartsHandler _linkHandler; /** The URL handler for images. */ private final LinkPartsHandler _imageHandler; /** A final pass over URLs to apply any last-minute changes. */ private final URLOutputFilter _urlOutputFilter; /** List of attachments on the page. */ private Collection<AttachmentHistory> _attachments = null; public Optional<PageStore> store() { return _store; } public PageStore unsafeStore() { return _store.get(); } public PageInfo page() { return _page; } public LinkPartsHandler linkHandler() { return _linkHandler; } public LinkPartsHandler imageHandler() { return _imageHandler; } public URLOutputFilter urlOutputFilter() { return _urlOutputFilter; } /** * Aggregate results produced by visitChildren. This returns the "right"most * non-null result found. */ @Override protected ASTNode aggregateResult(final ASTNode aggregate, final ASTNode nextResult) { return (nextResult == null) ? aggregate : nextResult; } /** * Construct a new AST builder. * * @param store The page store. * @param page The page being rendered. * @param urlOutputFilter The URL post-render processor. * @param handler The URL renderer */ private CreoleASTBuilder(final Optional<PageStore> store, final PageInfo page, final URLOutputFilter urlOutputFilter, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler) { _store = store; _page = page; _urlOutputFilter = urlOutputFilter; _linkHandler = linkHandler; _imageHandler = imageHandler; } /** Construct a new AST builder with a page store. */ public CreoleASTBuilder(final PageStore store, final PageInfo page, final URLOutputFilter urlOutputFilter, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler) { this(Optional.of(store), page, urlOutputFilter, linkHandler, imageHandler); } /** Construct a new AST builder without a page store. */ public CreoleASTBuilder(final PageInfo page, final URLOutputFilter urlOutputFilter, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler) { this(Optional.<PageStore> absent(), page, urlOutputFilter, linkHandler, imageHandler); } /** * Render some inline markup (like bold, italic, or strikethrough) by * converting the opening symbol into a plaintext AST node if the closing * symbol was missing. * * If italics is "//", this lets us render things like "//foo bar" as * "//foo bar" rather than, as ANTLR's error recovery would produce, " * <em>foo bar</em>". * * @param symbol The opening/closing symbol. * @param sname The name of the ending symbol * @param type The AST node class to use on success * @param end The (possibly missing) ending token. * @param inline The contents of the markup * @return Either an instance of the marked-up node if the ending token is * present, or an inline node consisting of a plaintext start token * followed by the rest of the rendered content. */ protected ASTNode renderInlineMarkup(final Class<? extends ASTNode> type, final String symbol, final String sname, final TerminalNode end, final InlineContext inline) { ASTNode inner = (inline != null) ? visit(inline) : new Plaintext(""); // If the end tag is missing, undo the error recovery if (end == null || ("<missing " + sname + ">").equals(end.getText())) { List<ASTNode> chunks = ImmutableList.of(new Plaintext(symbol), inner); return new Inline(chunks); } // If the inner text is missing, this is not markup if (inner.toXHTML().trim().equals("")) { List<ASTNode> chunks = ImmutableList.of(new Plaintext(symbol + symbol), inner); return new Inline(chunks); } try { Constructor<? extends ASTNode> constructor = type.getConstructor(ASTNode.class); return constructor.newInstance(inner); } catch (Exception e) { // Never reached if you pass in correct params // TODO: Get rid of this (a lambda to construct, rather than reflection, // would work) throw new RuntimeException(e); } } /** * Remove the ending tag (possibly followed by trailing whitespace) from a * string. * * @param node The body + ending tag. * @param end The ending tag text. * @return The body of the tag. */ protected String cutOffEndTag(final TerminalNode node, final String end) { String res = node.getText().replaceAll("\\s+$", ""); return res.substring(0, res.length() - end.length()); } /** * Render an inline piece of code with syntax highlighting. * * @param code The token containing the code * @param end The end marker * @param language The language to use * @return An inline code node with the end token stripped. */ protected ASTNode renderInlineCode(final TerminalNode node, final String end, final String language) { String code = cutOffEndTag(node, end); try { return new InlineCode(code, XhtmlRendererFactory.getRenderer(language)); } catch (IOException e) { return new InlineCode(code); } } /** * Render some inline code without syntax highlighting. */ protected ASTNode renderInlineCode(final TerminalNode node, final String end) { return new InlineCode(cutOffEndTag(node, end)); } /** * Render a block of code with syntax highlighting. See * {@link #renderInlineCode}. */ protected ASTNode renderBlockCode(final TerminalNode node, final String end, final String language) { String code = node.getText(); code = code.substring(0, code.length() - end.length()); try { return new Code(code, XhtmlRendererFactory.getRenderer(language)); } catch (IOException e) { return new Code(code); } } /** * Render a block of code without syntax highlighting. */ protected ASTNode renderBlockCode(final TerminalNode node, final String end) { return new Code(cutOffEndTag(node, end)); } /** * Class to hold the context of a list item to render. */ protected class ListItemContext { private final ParserRuleContext _ordered; private final ParserRuleContext _unordered; public ListItemContext(final ParserRuleContext ordered, final ParserRuleContext unordered) { _ordered = ordered; _unordered = unordered; } public ParserRuleContext get() { return ordered() ? _ordered : _unordered; } public boolean ordered() { return _ordered != null; } } /** Types of list contexts */ protected enum ListCtxType { List2Context, List3Context, List4Context, List5Context, List6Context, List7Context, List8Context, List9Context, List10Context }; /** Get the ordered component of a list context. */ protected ParserRuleContext olist(final ParserRuleContext ctx) { switch (ListCtxType.valueOf(ctx.getClass().getSimpleName())) { case List2Context: return ((List2Context) ctx).olist2(); case List3Context: return ((List3Context) ctx).olist3(); case List4Context: return ((List4Context) ctx).olist4(); case List5Context: return ((List5Context) ctx).olist5(); case List6Context: return ((List6Context) ctx).olist6(); case List7Context: return ((List7Context) ctx).olist7(); case List8Context: return ((List8Context) ctx).olist8(); case List9Context: return ((List9Context) ctx).olist9(); case List10Context: return ((List10Context) ctx).olist10(); default: throw new RuntimeException("Unknown list context type"); } } /** Get the unordered component of a list context. */ protected ParserRuleContext ulist(final ParserRuleContext ctx) { switch (ListCtxType.valueOf(ctx.getClass().getSimpleName())) { case List2Context: return ((List2Context) ctx).ulist2(); case List3Context: return ((List3Context) ctx).ulist3(); case List4Context: return ((List4Context) ctx).ulist4(); case List5Context: return ((List5Context) ctx).ulist5(); case List6Context: return ((List6Context) ctx).ulist6(); case List7Context: return ((List7Context) ctx).ulist7(); case List8Context: return ((List8Context) ctx).ulist8(); case List9Context: return ((List9Context) ctx).ulist9(); case List10Context: return ((List10Context) ctx).ulist10(); default: throw new RuntimeException("Unknown list context type"); } } /** * Render a list item. * * @param childContexts List of child elements * @param inner List of inner elements. * @return A list item containing with the given child list elements. */ protected ASTNode renderListItem(final List<? extends ParserRuleContext> childContexts, final InListContext inner) { List<ASTNode> parts = new ArrayList<ASTNode>(); for (ParserRuleContext in : inner.listBlock()) { if (in != null) { parts.add(visit(in)); } } if (!childContexts.isEmpty()) { // In general, a list can contain any arbitrary combination of ordered and // unordered sublists, and we want to preserve the (un)orderedness in the // bullet points, so we have to render them all individually. boolean isOrdered = false; List<ASTNode> items = new ArrayList<ASTNode>(); // Build lists of (un)ordered chunks one at a time, rendering them, and // adding to the list of lists. for (ParserRuleContext ctx : childContexts) { ListItemContext child = new ListItemContext(olist(ctx), ulist(ctx)); if (child.ordered() != isOrdered) { parts.add(isOrdered ? new OrderedList(items) : new UnorderedList(items)); items.clear(); } isOrdered = child.ordered(); items.add(visit(child.get())); } if (!items.isEmpty()) { parts.add(isOrdered ? new OrderedList(items) : new UnorderedList(items)); } } return new ListItem(parts); } /** * Check if the page has the named attachment. * * @param name Filename of the attachment. */ protected boolean hasAttachment(final String name) { // If there's no store, say we have no attachments. if (!store().isPresent()) { return false; } try { // Cache the attachments list if (_attachments == null) { _attachments = unsafeStore().attachments(page()); } // Read through the list. for (AttachmentHistory attachment : _attachments) { if (!attachment.isAttachmentDeleted() && attachment.getName().equals(name)) { return true; } } } catch (PageStoreException e) { } return false; } /** * If a paragraph starts with a sequence of blockable elements, separated by * newlines, render them as blocks and the remaining text (if any) as a * paragraph following this. * * @param paragraph The paragraph to expand out. * @param reversed Whether the paragraph is reversed or not. If so, the final * trailing paragraph has its chunks reversed, to ease re-ordering * later. * @return A list of blocks, which may just consist of the original paragraph. */ protected List<ASTNode> expandParagraph(final Paragraph paragraph, final boolean reversed) { ASTNode inline = paragraph.getChildren().get(0); List<ASTNode> chunks = inline.getChildren(); int numchunks = chunks.size(); // Drop empty inlines, as that means we've examined an entire paragraph. if (numchunks == 0) { return new ArrayList<ASTNode>(); } ASTNode head = chunks.get(0); String sep = (numchunks > 1) ? chunks.get(1).toXHTML() : "\r\n"; List<ASTNode> tail = (numchunks > 1) ? chunks.subList(1, numchunks) : new ArrayList<ASTNode>(); Paragraph rest = new Paragraph(new Inline(tail)); List<ASTNode> out = new ArrayList<ASTNode>(); // Drop leading whitespace if (head.toXHTML().matches("^\r?\n$")) { return expandParagraph(rest, reversed); } // Only continue if there is a hope of expanding it if (head instanceof BlockableNode) { // Check if we have a valid separator ASTNode block = null; if (sep == null || (!reversed && (sep.startsWith("\r\n") || sep.startsWith("\n")) || (reversed && sep.endsWith("\n")) || sep.startsWith("<br"))) { block = ((BlockableNode) head).toBlock(); } // Check if we have a match, and build the result list. if (block != null) { out.add(block); out.addAll(expandParagraph(rest, reversed)); return out; } } if (reversed) { List<ASTNode> rchunks = new ArrayList<ASTNode>(inline.getChildren()); Collections.reverse(rchunks); out.add(new Paragraph(new Inline(rchunks))); } else { out.add(paragraph); } return out; } }
package net.sf.mzmine.methods.filtering.mean; import org.w3c.dom.Element; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import net.sf.mzmine.util.Logger; import net.sf.mzmine.methods.MethodParameters; /** * This class represents parameter for the mean filter method */ public class MeanFilterParameters implements MethodParameters { /** * These Strings are used to access parameter values in an XML element */ private static final String tagName = "MeanFilterParameters"; private static final String oneSidedWindowLengthAttributeName = "OneSidedWindowLength"; /** * One-sided window length. Value is in MZ. True window size is two times this (plus-minus) */ public double oneSidedWindowLength = (double)0.1; /** * @return parameters in human readable form */ public String toString() { return new String("One-sided window length = " + oneSidedWindowLength + "Da"); } /** * * @return parameters represented by XML element */ public Element addToXML(Document doc) { Element e = doc.createElement(tagName); e.setAttribute(oneSidedWindowLengthAttributeName, String.valueOf(oneSidedWindowLength)); return e; } /** * Reads parameters from XML * @param doc XML document supposed to contain parameters for the method (may not contain them, though) */ public void readFromXML(Element element) { // Find my element NodeList n = element.getElementsByTagName(tagName); if ((n==null) || (n.getLength()<1)) return; Element myElement = (Element)(n.item(0)); // Set values String attrValue; attrValue = myElement.getAttribute(oneSidedWindowLengthAttributeName); try { oneSidedWindowLength = Double.parseDouble(attrValue); } catch (NumberFormatException nfe) {} } public MeanFilterParameters clone() { MeanFilterParameters myClone = new MeanFilterParameters(); myClone.oneSidedWindowLength = oneSidedWindowLength; return myClone; } }
package nl.vu.cs.querypie.reasoner.actions.incr; import nl.vu.cs.ajira.actions.Action; import nl.vu.cs.ajira.actions.ActionConf; import nl.vu.cs.ajira.actions.ActionContext; import nl.vu.cs.ajira.actions.ActionFactory; import nl.vu.cs.ajira.actions.ActionOutput; import nl.vu.cs.ajira.actions.ActionSequence; import nl.vu.cs.ajira.data.types.TInt; import nl.vu.cs.ajira.data.types.TLong; import nl.vu.cs.ajira.data.types.Tuple; import nl.vu.cs.ajira.data.types.TupleFactory; import nl.vu.cs.ajira.exceptions.ActionNotConfiguredException; import nl.vu.cs.querypie.reasoner.actions.common.ActionsHelper; import nl.vu.cs.querypie.reasoner.support.Consts; import nl.vu.cs.querypie.reasoner.support.ParamHandler; import nl.vu.cs.querypie.storage.inmemory.TupleSet; import nl.vu.cs.querypie.storage.inmemory.TupleSetImpl; import nl.vu.cs.querypie.storage.inmemory.TupleStepMap; public class IncrAddController extends Action { public static void addToChain(int step, boolean firstIteration, ActionSequence actions) throws ActionNotConfiguredException { ActionConf c = ActionFactory.getActionConf(IncrAddController.class); c.setParamInt(IncrAddController.I_STEP, step); c.setParamBoolean(IncrAddController.B_FIRST_ITERATION, firstIteration); actions.add(c); } public static final int I_STEP = 0; public static final int B_FIRST_ITERATION = 1; private TupleSet currentDelta; private Tuple currentTuple; private int step; private boolean firstIteration; @Override public void registerActionParameters(ActionConf conf) { conf.registerParameter(I_STEP, "I_STEP", 0, true); conf.registerParameter(B_FIRST_ITERATION, "B_FIRST_ITERATION", true, false); } @Override public void startProcess(ActionContext context) throws Exception { step = getParamInt(I_STEP); firstIteration = getParamBoolean(B_FIRST_ITERATION); currentDelta = new TupleSetImpl(); currentTuple = TupleFactory.newTuple(new TLong(), new TLong(), new TLong(), new TInt()); } @Override public void process(Tuple tuple, ActionContext context, ActionOutput actionOutput) throws Exception { if (firstIteration) { return; } tuple.copyTo(currentTuple); Object completeDeltaObj = context .getObjectFromCache(Consts.COMPLETE_DELTA_KEY); if (completeDeltaObj instanceof TupleSet) { TupleSet completeDelta = (TupleSet) completeDeltaObj; if (completeDelta.add(currentTuple)) { currentDelta.add(currentTuple); currentTuple = TupleFactory.newTuple(); } } else { TupleStepMap completeDelta = (TupleStepMap) completeDeltaObj; if (!completeDelta.containsKey(tuple)) { currentDelta.add(currentTuple); } completeDelta.put(currentTuple, 1); currentTuple = TupleFactory.newTuple(); } } @Override public void stopProcess(ActionContext context, ActionOutput actionOutput) throws Exception { // In case of new derivations, perform another iteration if (firstIteration) { executeOneForwardChainingIterationAndRestart(context, actionOutput); } else if (!currentDelta.isEmpty()) { saveCurrentDelta(context); executeOneForwardChainingIterationAndRestart(context, actionOutput); } else { // Otherwise stop and write complete derivations on btree ParamHandler.get().setLastStep(step); writeCompleteDeltaToBTree(context, actionOutput); } } private void executeOneForwardChainingIterationAndRestart( ActionContext context, ActionOutput actionOutput) throws Exception { ActionSequence actions = new ActionSequence(); IncrRulesParallelExecution.addToChain(step, actions); ActionsHelper.collectToNode(false, actions); IncrAddController.addToChain(step + 1, false, actions); actionOutput.branch(actions); } private void saveCurrentDelta(ActionContext context) { context.putObjectInCache(Consts.CURRENT_DELTA_KEY, currentDelta); } private void writeCompleteDeltaToBTree(ActionContext context, ActionOutput actionOutput) throws Exception { ActionsHelper.writeInMemoryTuplesToBTree(context, actionOutput, Consts.COMPLETE_DELTA_KEY); } }
package openccsensors.common.sensorcard; import ic2.api.EnergyNet; import ic2.api.IEnergyConductor; import ic2.api.IEnergySink; import ic2.api.IEnergySource; import ic2.api.IEnergyStorage; import ic2.api.IReactor; import ic2.api.IReactorChamber; import ic2.api.Ic2Recipes; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction; import net.minecraft.src.CreativeTabs; import net.minecraft.src.IInventory; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import net.minecraft.src.TileEntity; import net.minecraft.src.World; import openccsensors.common.core.ISensorCard; import openccsensors.common.core.ISensorInterface; import openccsensors.common.core.SensorHelper; public class IndustrialCraftSensorCard extends Item implements ISensorCard { public IndustrialCraftSensorCard(int par1) { super(par1); setCreativeTab(CreativeTabs.tabRedstone); } @Override public ISensorInterface getSensorInterface(ItemStack itemstack, boolean turtle) { return new InventorySensorInterface(); } @Override public String getItemNameIS(ItemStack is) { return "openccsensors.item.industrialsensor"; } // Temporary! To differentiate this sensor card from the Inventory/Proximity one. @Override public int getIconFromDamage(int par1) { return 2; } public class InventorySensorInterface implements ISensorInterface { Map ic2EntityMap; @Override public String getName() { return "industrial"; } @Override public Map getBasicTarget(World world, int x, int y, int z) { Class[] validIC2Tiles = new Class[] { IReactor.class, IReactorChamber.class, IEnergyStorage.class, IEnergyConductor.class, IEnergySource.class, IEnergySink.class }; HashMap tileMap = SensorHelper.getAdjacentTile(world, x, y, z, validIC2Tiles); Iterator it = tileMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); TileEntity ic2Entity = (TileEntity)pairs.getValue(); if (!(ic2Entity instanceof IReactorChamber) || (((IReactorChamber)ic2Entity).getReactor() != null)) pairs.setValue(new IC2Target((TileEntity) pairs.getValue())); } ic2EntityMap = tileMap; HashMap retMap = new HashMap(); it = ic2EntityMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); retMap.put(pairs.getKey(), ((IC2Target) pairs.getValue()).getBasicInformation(world)); } return retMap; } @Override public Map getDetailTarget(World world, int x, int y, int z, String target) { IC2Target ic2Entity = (IC2Target) ic2EntityMap.get(target); return ic2Entity.getDetailInformation(world); } @Override public String[] getMethods() { return null; } @Override public Object[] callMethod(int methodID, Object[] args) throws Exception { return null; } } private class IC2Target { private int xCoord; private int yCoord; private int zCoord; private String interfaceType; private String name; IC2Target(TileEntity ic2Entity) { xCoord = ic2Entity.xCoord; yCoord = ic2Entity.yCoord; zCoord = ic2Entity.zCoord; if ((ic2Entity instanceof IReactor) || (ic2Entity instanceof IReactorChamber)) interfaceType = IReactor.class.getName(); else if (ic2Entity instanceof IEnergyStorage) interfaceType = IEnergyStorage.class.getName(); else if (ic2Entity instanceof IEnergyConductor) interfaceType = IEnergyConductor.class.getName(); else if (ic2Entity instanceof IEnergySink) interfaceType = IEnergySink.class.getName(); else if (ic2Entity instanceof IEnergySource) interfaceType = IEnergySource.class.getName(); else interfaceType = ic2Entity.getClass().getName(); } private HashMap populateReactorData(IReactor reactor) { HashMap rtn = null; if (reactor != null) { rtn = new HashMap(); rtn.put("heat", reactor.getHeat()); rtn.put("maxHeat", reactor.getMaxHeat()); rtn.put("powered", reactor.produceEnergy()); rtn.put("output", reactor.getOutput() * 5); IInventory reactorInventory = (IInventory)reactor; rtn.put("inventory", SensorHelper.invToMap(reactorInventory)); } return rtn; } private HashMap populateEnergyStorageData(IEnergyStorage storage) { HashMap rtn = null; if (storage != null) { rtn = new HashMap(); rtn.put("stored", storage.getStored()); rtn.put("capacity", storage.getCapacity()); rtn.put("output", storage.getOutput()); } return rtn; } private HashMap populateEnergyConducted(World world, TileEntity tile) { HashMap rtn = null; if (tile != null) { rtn = new HashMap(); Long energyConducted = EnergyNet.getForWorld(world).getTotalEnergyConducted((TileEntity)tile); rtn.put("energyConducted", energyConducted); } return rtn; } public Map getBasicInformation(World world) { HashMap retMap = new HashMap(); retMap.put("type", SensorHelper.getType(interfaceType)); // abuse translation system to translate obsfucated/dev names return retMap; } public Map getDetailInformation(World world) { HashMap retMap = null; TileEntity tile = world.getBlockTileEntity(xCoord, yCoord, zCoord); if (tile != null) { if (IReactor.class.isInstance(tile)) retMap = populateReactorData((IReactor)tile); else if (IReactorChamber.class.isInstance(tile)) retMap = populateReactorData(((IReactorChamber)tile).getReactor()); else if (IEnergyStorage.class.isInstance(tile)) retMap = populateEnergyStorageData((IEnergyStorage)tile); else retMap = populateEnergyConducted(world, tile); } return retMap; } } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.portletcontainer; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.PersistenceManagerException; import org.gridlab.gridsphere.core.persistence.hibernate.DatabaseTask; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.*; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); private static PortletRegistry registry = PortletRegistry.getInstance(); private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { // discover portlets log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createUserPortletService(PortletManagerService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); // create groups from portlet web apps log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createUserPortletService(AccessControlManagerService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createUserPortletService(UserManagerService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createUserPortletService(LoginService.class, GuestUser.getInstance(), getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { GridSphereEvent event = new GridSphereEventImpl(aclService, context, req, res); PortletRequest portletReq = event.getPortletRequest(); PortletResponse portletRes = event.getPortletResponse(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/persistence/")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/dberror.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize needed services initializeServices(); // initialize all portlets PortletInvoker.initAllPortlets(portletReq, portletRes); } catch (PortletException e) { req.setAttribute(SportletProperties.ERROR, e); } layoutEngine = PortletLayoutEngine.getInstance(); firstDoGet = Boolean.FALSE; } } setUserAndGroups(portletReq); setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(aclService, context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); setTCKUser(portletReq); layoutEngine.service(event); log.debug("Session stats"); userSessionManager.dumpSessions(); log.debug("Portlet service factory stats"); factory.logStatistics(); log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); Map l = new HashMap(); l.put(SportletGroup.CORE, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(PortletGroupFactory.GRIDSPHERE_GROUP, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup)it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); String username = req.getParameter("ui_tf_username_"); String password = req.getParameter("ui_pb_password_"); try { User user = loginService.login(username, password); // null out passwd password = null; req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 0.9"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { log.debug("contextInitialized()"); ServletContext ctx = event.getServletContext(); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
package evaluation.evalBench.session; import java.util.ArrayList; import java.util.Hashtable; import evaluation.evalBench.EvaluationManager; import evaluation.evalBench.io.EvaluationSessionJournal; import evaluation.evalBench.task.Task; /** * EvaluationSession is responsible for managing a single evaluation session. * It holds an array of {@link Task} instances and the corresponding configurations like * data set, visualization type .. * It is possible to set the order of the task list to random or sequential (in the order the tasks were added) * * This class is also responsible for managing the journal for this session * (i.e. when was a task started, how long was the duration for that task, * what the test person did answer,.. ) * * */ public class EvaluationSession { private ArrayList<Task> m_taskList; private ArrayList<Task> m_finishedTaskList; private String m_title; private Task m_currentTask; private Hashtable<String, String> m_configuration; private EvaluationSessionGroup m_sessionGroup = null; private EvaluationSessionJournal m_journal; private boolean m_sessionCompleted; private boolean m_randomOrder; /** * Constructor taking a session titles * @param sessionTitle */ public EvaluationSession(String sessionTitle){ super(); m_title = sessionTitle; m_taskList = new ArrayList<Task>(); m_finishedTaskList = new ArrayList<Task>(); m_configuration = new Hashtable<String,String>(); m_sessionCompleted = false; m_randomOrder = false; } /** * * @return the {@link EvaluationSessionJournal} of this session */ public EvaluationSessionJournal getJournal() { return m_journal; } /** * set the {@link EvaluationSessionJournal} of this session * @param aJournal */ public void setJournal(EvaluationSessionJournal aJournal) { this.m_journal = aJournal; } /** * triggers the creation of a journal */ public void startSession(){ m_sessionCompleted = false; m_journal = EvaluationManager.getInstance().getJournalForSession(this); } /** * * @return true if the tasks are executed in random order, false if sequential */ public boolean isRandomOrder() { return m_randomOrder; } /** * set the order of task execution (random or sequential) * @param m_randomOrder */ public void setRandomOrder(boolean m_randomOrder) { this.m_randomOrder = m_randomOrder; } /** * * @return the title of the session */ public String getTitle() { return m_title; } /** * set the title for the session * @param title session title */ public void setTitle(String title) { m_title = title; } /** * configurations like data set, visualization type .. * @return a {@link java.util.Hashtable} with the configuration in value/key pairs */ public Hashtable<String,String> getConfiguration() { return m_configuration; } /** * set configurations like data set, visualization type .. * @param aConfiguration */ public void setConfiguration(Hashtable<String,String> aConfiguration) { this.m_configuration = aConfiguration; } /** * * @return the evaluation session group */ public EvaluationSessionGroup getSessionGroup() { return m_sessionGroup; } /** * set the evaluation session group * @param sessionGroup */ void setSessionGroup(EvaluationSessionGroup sessionGroup) { this.m_sessionGroup = sessionGroup; } /** * add a single task to the session * @param aTask */ public void addTask(Task aTask){ m_taskList.add(aTask); m_sessionCompleted = false; } public void addTask(Task aTask, int idx){ m_taskList.add(idx, aTask); m_sessionCompleted = false; } /** * set an array list of tasks for this session * previously added tasks are deleted * @param taskList */ public void setTaskList(ArrayList<Task> taskList){ if (taskList!=null){ this.m_taskList = taskList; m_sessionCompleted = false; } } /** * records the current task to the journal and adds it to the finished task list * currentTask is set to null */ private void setCurrentTaskFinished(){ if (m_currentTask != null){ if (m_journal == null){ m_journal = EvaluationManager.getInstance().getJournalForSession(this); } m_journal.recordTask(m_currentTask); m_finishedTaskList.add(m_currentTask); m_currentTask = null; } } /** * removes the given task from the unfinished tasklist and sets it as current task * @param aTask */ private void setCurrentTask(Task aTask){ int taskIndex = m_taskList.indexOf(aTask); if (taskIndex != -1){ m_taskList.remove(taskIndex); m_currentTask = aTask; } } /** * provides the currently active task * @return */ public Task getCurrentTask(){ return m_currentTask; } /** * * @return true, if more tasks are available, false if every task was already finished */ public boolean hasMoreTasks(){ return !m_taskList.isEmpty(); } /** * get the next task from the list. the order is either sequential or randomized * @return null if no task is available (every task was finished) */ public Task getNextTask(){ setCurrentTaskFinished(); if (this.hasMoreTasks()){ if (m_randomOrder) { // pick a random task java.util.Random random = new java.util.Random(); int index = random.nextInt(m_taskList.size()); Task aTask = m_taskList.get(index); this.setCurrentTask(aTask); return aTask; }else { // pick the task on index 0 Task aTask = m_taskList.get(0); this.setCurrentTask(aTask); return aTask; } } // no task available, session is completed m_sessionCompleted = true; m_journal.sessionFinished(); return null; } /** * * @return true, if every task is finished */ public boolean isSessionCompleted() { return m_sessionCompleted; } public int getTotalTaskCount() { return m_taskList.size() + m_finishedTaskList.size() + (m_currentTask != null ? 1 : 0); } /** * zero based. * @return */ public int getCurrentTaskIndex() { return m_finishedTaskList.size(); } @Override public String toString() { return m_title; } }
package org.intellij.ibatis.provider; import com.intellij.codeInsight.lookup.LookupValueFactory; import com.intellij.psi.*; import org.intellij.ibatis.IbatisManager; import org.intellij.ibatis.dom.sqlMap.*; import org.intellij.ibatis.util.IbatisConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * statement id reference */ public class StatementIdReferenceProvider extends BaseReferenceProvider { @NotNull public PsiReference[] getReferencesByElement(final PsiElement psiElement) { if (!(psiElement instanceof PsiLiteralExpression)) return PsiReference.EMPTY_ARRAY; PsiElement parent = psiElement.getParent().getParent(); if (parent == null || !(parent instanceof PsiMethodCallExpression)) { return PsiReference.EMPTY_ARRAY; } //method name validation simply, filter for detailed validation String[] path = ((PsiMethodCallExpression) parent).getMethodExpression().getText().split("\\."); String methodName = path[path.length - 1].trim().toLowerCase(); if (!methodName.matches(SqlClientElementFilter.operationPattern)) return PsiReference.EMPTY_ARRAY; return new PsiReference[]{new StatementIdReference(methodName, (PsiLiteralExpression) psiElement, false)}; } public class StatementIdReference extends PsiReferenceBase<PsiLiteralExpression> { private String methodName = null; public StatementIdReference(String methodName, PsiLiteralExpression expression, boolean soft) { super(expression, soft); this.methodName = methodName.toLowerCase(); } @Nullable public PsiElement resolve() { IbatisManager manager = IbatisManager.getInstance(); String statementId = getCanonicalText(); if (methodName.contains("insert")) { Insert insert = manager.getAllInsert(getElement()).get(statementId); return insert == null ? null : insert.getXmlTag(); } else if (methodName.contains("update")) { Update update = manager.getAllUpdate(getElement()).get(statementId); if (update != null) { return update.getXmlTag(); } Delete delete = manager.getAllDelete(getElement()).get(statementId); if (delete != null) { return delete.getXmlTag(); } Procedure procedure = manager.getAllProcedure(getElement()).get(statementId); if (procedure != null) { return procedure.getXmlTag(); } Insert insert = manager.getAllInsert(getElement()).get(statementId); if (insert != null) { return insert.getXmlTag(); } return null; // return update == null ? null : update.getXmlTag(); } else if (methodName.contains("delete")) { Delete delete = manager.getAllDelete(getElement()).get(statementId); return delete == null ? null : delete.getXmlTag(); } else { Select select = manager.getAllSelect(getElement()).get(statementId); if (select != null) return select.getXmlTag(); Statement statement = manager.getAllStatement(getElement()).get(statementId); if (statement != null) return statement.getXmlTag(); Procedure procedure = manager.getAllProcedure(getElement()).get(statementId); return procedure == null ? null : procedure.getXmlTag(); } } public Object[] getVariants() { List<Object> variants = new ArrayList<Object>(); IbatisManager manager = IbatisManager.getInstance(); if (methodName.contains("insert")) { //insert Set<String> allInsert = manager.getAllInsert(getElement()).keySet(); for (String insert : allInsert) { variants.add(LookupValueFactory.createLookupValue(insert, IbatisConstants.SQLMAP_INSERT)); } } else if (methodName.contains("update")) { //update Set<String> allUpate = manager.getAllUpdate(getElement()).keySet(); for (String update : allUpate) { variants.add(LookupValueFactory.createLookupValue(update, IbatisConstants.SQLMAP_UPDATE)); } Set<String> allDelete = manager.getAllDelete(getElement()).keySet(); for (String delete : allDelete) { variants.add(LookupValueFactory.createLookupValue(delete, IbatisConstants.SQLMAP_DELETE)); } Set<String> allProcedure = manager.getAllProcedure(getElement()).keySet(); for (String procedure : allProcedure) { variants.add(LookupValueFactory.createLookupValue(procedure, IbatisConstants.SQLMAP_PROCEDURE)); } Set<String> allInsert = manager.getAllInsert(getElement()).keySet(); for (String insert : allInsert) { variants.add(LookupValueFactory.createLookupValue(insert, IbatisConstants.SQLMAP_INSERT)); } } else if (methodName.contains("delete")) { //delete Set<String> allDelete = manager.getAllDelete(getElement()).keySet(); for (String delete : allDelete) { variants.add(LookupValueFactory.createLookupValue(delete, IbatisConstants.SQLMAP_DELETE)); } } else { //select and statement Set<String> allSelect = manager.getAllSelect(getElement()).keySet(); for (String select : allSelect) { variants.add(LookupValueFactory.createLookupValue(select, IbatisConstants.SQLMAP_SELECT)); } Set<String> allStatement = manager.getAllStatement(getElement()).keySet(); for (String statement : allStatement) { variants.add(LookupValueFactory.createLookupValue(statement, IbatisConstants.SQLMAP_STATEMENT)); } Set<String> allProcedure = manager.getAllProcedure(getElement()).keySet(); for (String procedure : allProcedure) { variants.add(LookupValueFactory.createLookupValue(procedure, IbatisConstants.SQLMAP_PROCEDURE)); } } return variants.toArray(); } public boolean isSoft() { return false; } } }
package org.mtransit.android.commons.provider; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.mtransit.android.commons.ArrayUtils; import org.mtransit.android.commons.LocaleUtils; import org.mtransit.android.commons.MTLog; import org.mtransit.android.commons.PreferenceUtils; import org.mtransit.android.commons.R; import org.mtransit.android.commons.SqlUtils; import org.mtransit.android.commons.StringUtils; import org.mtransit.android.commons.TimeUtils; import org.mtransit.android.commons.UriUtils; import org.mtransit.android.commons.data.News; import twitter4j.User; import android.annotation.SuppressLint; import android.content.Context; import android.content.UriMatcher; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.text.TextUtils; @SuppressLint("Registered") public class TwitterNewsProvider extends NewsProvider { private static final String TAG = TwitterNewsProvider.class.getSimpleName(); @Override public String getLogTag() { return TAG; } /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ private static final String PREF_KEY_AGENCY_LAST_UPDATE_MS = TwitterNewsDbHelper.PREF_KEY_AGENCY_LAST_UPDATE_MS; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ private static final String PREF_KEY_AGENCY_LAST_UPDATE_LANG = TwitterNewsDbHelper.PREF_KEY_AGENCY_LAST_UPDATE_LANG; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ private static final String PREF_KEY_ACCESS_TOKEN = "pTwitterAccessToken"; private static UriMatcher uriMatcher = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static UriMatcher getURIMATCHER(Context context) { if (uriMatcher == null) { uriMatcher = getNewUriMatcher(getAUTHORITY(context)); } return uriMatcher; } private static String authority = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static String getAUTHORITY(Context context) { if (authority == null) { authority = context.getResources().getString(R.string.twitter_authority); } return authority; } private static Uri authorityUri = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static Uri getAUTHORITY_URI(Context context) { if (authorityUri == null) { authorityUri = UriUtils.newContentUri(getAUTHORITY(context)); } return authorityUri; } private static String targetAuthority = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static String getTARGET_AUTHORITY(Context context) { if (targetAuthority == null) { targetAuthority = context.getResources().getString(R.string.twitter_target_for_poi_authority); } return targetAuthority; } private static String consumerKey = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static String getCONSUMER_KEY(Context context) { if (consumerKey == null) { consumerKey = context.getResources().getString(R.string.twitter_consumer_key); } return consumerKey; } private static String consumerSecret = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static String getCONSUMER_SECRET(Context context) { if (consumerSecret == null) { consumerSecret = context.getResources().getString(R.string.twitter_consumer_secret); } return consumerSecret; } private static String color = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static String getCOLOR(Context context) { if (color == null) { color = context.getResources().getString(R.string.twitter_color); } return color; } private static java.util.List<String> screenNames = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static java.util.List<String> getSCREEN_NAMES(Context context) { if (screenNames == null) { screenNames = Arrays.asList(context.getResources().getStringArray(R.array.twitter_screen_names)); } return screenNames; } private static java.util.List<String> screenNamesLang = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static java.util.List<String> getSCREEN_NAMES_LANG(Context context) { if (screenNamesLang == null) { screenNamesLang = Arrays.asList(context.getResources().getStringArray(R.array.twitter_screen_names_lang)); } return screenNamesLang; } private static java.util.List<String> screenNamesColors = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static java.util.List<String> getSCREEN_NAMES_COLORS(Context context) { if (screenNamesColors == null) { screenNamesColors = Arrays.asList(context.getResources().getStringArray(R.array.twitter_screen_names_colors)); } return screenNamesColors; } private static java.util.List<String> screenNamesTargets = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static java.util.List<String> getSCREEN_NAMES_TARGETS(Context context) { if (screenNamesTargets == null) { screenNamesTargets = Arrays.asList(context.getResources().getStringArray(R.array.twitter_screen_names_target)); } return screenNamesTargets; } private static java.util.List<Integer> screenNamesSeverity = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static java.util.List<Integer> getSCREEN_NAMES_SEVERITY(Context context) { if (screenNamesSeverity == null) { screenNamesSeverity = ArrayUtils.asIntegerList(context.getResources().getIntArray(R.array.twitter_screen_names_severity)); } return screenNamesSeverity; } private static java.util.List<Long> screenNamesNoteworthy = null; /** * Override if multiple {@link TwitterNewsProvider} implementations in same app. */ public static java.util.List<Long> getSCREEN_NAMES_NOTEWORTHY(Context context) { if (screenNamesNoteworthy == null) { screenNamesNoteworthy = ArrayUtils.asLongList(context.getResources().getStringArray(R.array.twitter_screen_names_noteworthy)); } return screenNamesNoteworthy; } private static String accessToken = null; public static String getACCESS_TOKEN(Context context) { if (accessToken == null) { accessToken = PreferenceUtils.getPrefLcl(context, PREF_KEY_ACCESS_TOKEN, StringUtils.EMPTY); } return accessToken; } public static void setACCESS_TOKEN(Context context, String newAccessToken) { accessToken = newAccessToken; PreferenceUtils.savePrefLcl(context, PREF_KEY_ACCESS_TOKEN, accessToken, false); // asynchronous } @Override public UriMatcher getURI_MATCHER() { return getURIMATCHER(getContext()); } private static TwitterNewsDbHelper dbHelper; private static int currentDbVersion = -1; private TwitterNewsDbHelper getDBHelper(Context context) { if (dbHelper == null) { // initialize dbHelper = getNewDbHelper(context); currentDbVersion = getCurrentDbVersion(); } else { // reset try { if (currentDbVersion != getCurrentDbVersion()) { dbHelper.close(); dbHelper = null; return getDBHelper(context); } } catch (Exception e) { // fail if locked, will try again later MTLog.w(this, e, "Can't check DB version!"); } } return dbHelper; } /** * Override if multiple {@link TwitterNewsDbHelper} implementations in same app. */ public int getCurrentDbVersion() { return TwitterNewsDbHelper.getDbVersion(getContext()); } /** * Override if multiple {@link TwitterNewsDbHelper} implementations in same app. */ public TwitterNewsDbHelper getNewDbHelper(Context context) { return new TwitterNewsDbHelper(context.getApplicationContext()); } @Override public SQLiteOpenHelper getDBHelper() { return getDBHelper(getContext()); } private static final long NEWS_MAX_VALIDITY_IN_MS = Long.MAX_VALUE; // FOREVER private static final long NEWS_VALIDITY_IN_MS = TimeUnit.HOURS.toMillis(1); private static final long NEWS_VALIDITY_IN_FOCUS_IN_MS = TimeUnit.MINUTES.toMillis(10); private static final long NEWS_MIN_DURATION_BETWEEN_REFRESH_IN_MS = TimeUnit.MINUTES.toMillis(10); private static final long NEWS_MIN_DURATION_BETWEEN_REFRESH_IN_FOCUS_IN_MS = TimeUnit.MINUTES.toMillis(1); @Override public long getMinDurationBetweenNewsRefreshInMs(boolean inFocus) { if (inFocus) { return NEWS_MIN_DURATION_BETWEEN_REFRESH_IN_FOCUS_IN_MS; } return NEWS_MIN_DURATION_BETWEEN_REFRESH_IN_MS; } @Override public long getNewsMaxValidityInMs() { return NEWS_MAX_VALIDITY_IN_MS; } @Override public long getNewsValidityInMs(boolean inFocus) { if (inFocus) { return NEWS_VALIDITY_IN_FOCUS_IN_MS; } return NEWS_VALIDITY_IN_MS; } @Override public boolean purgeUselessCachedNews() { return NewsProvider.purgeUselessCachedNews(this); } @Override public boolean deleteCachedNews(Integer serviceUpdateId) { return NewsProvider.deleteCachedNews(this, serviceUpdateId); } private int deleteAllAgencyNewsData() { int affectedRows = 0; try { String selection = SqlUtils.getWhereEqualsString(NewsProviderContract.Columns.T_NEWS_K_SOURCE_ID, AGENCY_SOURCE_ID); affectedRows = getDBHelper().getWritableDatabase().delete(getNewsDbTableName(), selection, null); } catch (Exception e) { MTLog.w(this, e, "Error while deleting all agency news data!"); } return affectedRows; } @Override public String getAuthority() { return getAUTHORITY(getContext()); } @Override public Uri getAuthorityUri() { return getAUTHORITY_URI(getContext()); } @Override public void cacheNews(ArrayList<News> newNews) { NewsProvider.cacheNewsS(this, newNews); } @Override public ArrayList<News> getCachedNews(NewsProviderContract.Filter newsFilter) { if (newsFilter == null) { MTLog.w(this, "getCachedNews() > skip (no news filter)"); return null; } ArrayList<News> cachedNews = NewsProvider.getCachedNewsS(this, newsFilter); return cachedNews; } @Override public ArrayList<News> getNewNews(NewsProviderContract.Filter newsFilter) { if (newsFilter == null) { MTLog.w(this, "getNewNews() > no new service update (filter null)"); return null; } updateAgencyNewsDataIfRequired(newsFilter.isInFocusOrDefault()); ArrayList<News> cachedNews = getCachedNews(newsFilter); return cachedNews; } private static final String AGENCY_SOURCE_ID = "twitter"; private static final String AGENCY_SOURCE_LABEL = "Twitter"; private void updateAgencyNewsDataIfRequired(boolean inFocus) { long lastUpdateInMs = PreferenceUtils.getPrefLcl(getContext(), PREF_KEY_AGENCY_LAST_UPDATE_MS, 0l); String lastUpdateLang = PreferenceUtils.getPrefLcl(getContext(), PREF_KEY_AGENCY_LAST_UPDATE_LANG, StringUtils.EMPTY); long minUpdateMs = Math.min(getNewsMaxValidityInMs(), getNewsValidityInMs(inFocus)); long nowInMs = TimeUtils.currentTimeMillis(); if (lastUpdateInMs + minUpdateMs > nowInMs && LocaleUtils.getDefaultLanguage().equals(lastUpdateLang)) { return; } updateAgencyNewsDataIfRequiredSync(lastUpdateInMs, lastUpdateLang, inFocus); } private synchronized void updateAgencyNewsDataIfRequiredSync(long lastUpdateInMs, String lastUpdateLang, boolean inFocus) { if (PreferenceUtils.getPrefLcl(getContext(), PREF_KEY_AGENCY_LAST_UPDATE_MS, 0l) > lastUpdateInMs && LocaleUtils.getDefaultLanguage().equals(lastUpdateLang)) { return; // too late, another thread already updated } long nowInMs = TimeUtils.currentTimeMillis(); boolean deleteAllRequired = false; if (lastUpdateInMs + getNewsMaxValidityInMs() < nowInMs || !LocaleUtils.getDefaultLanguage().equals(lastUpdateLang)) { deleteAllRequired = true; // too old to display } long minUpdateMs = Math.min(getNewsMaxValidityInMs(), getNewsValidityInMs(inFocus)); if (deleteAllRequired || lastUpdateInMs + minUpdateMs < nowInMs) { updateAllAgencyNewsDataFromWWW(deleteAllRequired); // try to update } } private void updateAllAgencyNewsDataFromWWW(boolean deleteAllRequired) { boolean deleteAllDone = false; if (deleteAllRequired) { deleteAllAgencyNewsData(); deleteAllDone = true; } ArrayList<News> newNews = loadAgencyNewsDataFromWWW(); if (newNews != null) { // empty is OK long nowInMs = TimeUtils.currentTimeMillis(); if (!deleteAllDone) { deleteAllAgencyNewsData(); } cacheNews(newNews); PreferenceUtils.savePrefLcl(getContext(), PREF_KEY_AGENCY_LAST_UPDATE_MS, nowInMs, true); // sync PreferenceUtils.savePrefLcl(getContext(), PREF_KEY_AGENCY_LAST_UPDATE_LANG, LocaleUtils.getDefaultLanguage(), true); // sync } // else keep whatever we have until max validity reached } private static final String TOKEN_TYPE_BEARER = "bearer"; private ArrayList<News> loadAgencyNewsDataFromWWW() { try { twitter4j.conf.ConfigurationBuilder builder = new twitter4j.conf.ConfigurationBuilder(); builder.setApplicationOnlyAuthEnabled(true); builder.setOAuthConsumerKey(getCONSUMER_KEY(getContext())); builder.setOAuthConsumerSecret(getCONSUMER_SECRET(getContext())); twitter4j.Twitter twitter = new twitter4j.TwitterFactory(builder.build()).getInstance(); String accessToken = getACCESS_TOKEN(getContext()); if (TextUtils.isEmpty(accessToken)) { twitter4j.auth.OAuth2Token token = twitter.getOAuth2Token(); if (TOKEN_TYPE_BEARER.equals(token.getTokenType())) { setACCESS_TOKEN(getContext(), token.getAccessToken()); } else { MTLog.w(this, "Unexpected token type '%s' in token '%s'!", token.getTokenType(), token); return null; } } else { twitter.setOAuth2Token(new twitter4j.auth.OAuth2Token(TOKEN_TYPE_BEARER, accessToken)); } ArrayList<News> newNews = new ArrayList<News>(); long maxValidityInMs = getNewsMaxValidityInMs(); String authority = getAUTHORITY(getContext()); int i = 0; for (String screenName : getSCREEN_NAMES(getContext())) { long newLastUpdateInMs = TimeUtils.currentTimeMillis(); twitter4j.ResponseList<twitter4j.Status> statuses = twitter.getUserTimeline(screenName); String target = getSCREEN_NAMES_TARGETS(getContext()).get(i); int severity = getSCREEN_NAMES_SEVERITY(getContext()).get(i); long noteworthyInMs = getSCREEN_NAMES_NOTEWORTHY(getContext()).get(i); String userLang = getSCREEN_NAMES_LANG(getContext()).get(i); if (!LocaleUtils.MULTIPLE.equals(userLang) && !LocaleUtils.UNKNOWN.equals(userLang) && !LocaleUtils.getDefaultLanguage().equals(userLang)) { i++; continue; } for (twitter4j.Status status : statuses) { if (status.getInReplyToUserId() >= 0) { continue; } String textHTML = getHTMLText(status); String lang = userLang; if (LocaleUtils.MULTIPLE.equals(lang)) { if (LocaleUtils.isFR(status.getLang())) { lang = Locale.FRENCH.getLanguage(); } else if (LocaleUtils.isEN(status.getLang())) { lang = Locale.ENGLISH.getLanguage(); } } if (TextUtils.isEmpty(lang)) { lang = LocaleUtils.UNKNOWN; } News news = new News(null, authority, AGENCY_SOURCE_ID + status.getId(), severity, noteworthyInMs, newLastUpdateInMs, maxValidityInMs, status.getCreatedAt().getTime(), target, getColor(status.getUser()), status.getUser().getName(), getUserName(status.getUser()), status.getUser().getProfileImageURLHttps(), getAuthorProfileURL(status.getUser()), status.getText(), textHTML, getNewsWebURL(status), lang, AGENCY_SOURCE_ID, AGENCY_SOURCE_LABEL); newNews.add(news); } i++; } return newNews; } catch (Exception e) { MTLog.e(TAG, e, "INTERNAL ERROR: Unknown Exception"); return null; } } private static Collection<String> languages = null; @Override public Collection<String> getNewsLanguages() { if (languages == null) { languages = new HashSet<String>(); if (LocaleUtils.isFR()) { languages.add(Locale.FRENCH.getLanguage()); } else { languages.add(Locale.ENGLISH.getLanguage()); } languages.add(LocaleUtils.UNKNOWN); } return languages; } private String getColor(User user) { try { return getSCREEN_NAMES_COLORS(getContext()).get(getSCREEN_NAMES(getContext()).indexOf(user.getScreenName())); } catch (Exception e) { MTLog.w(this, "Error while finding user '%s' color!", user); return getCOLOR(getContext()); } } private String getUserName(User user) { return String.format(MENTION_AND_SCREEN_NAME, user.getScreenName()); } private static final String HASHTAG_AND_TAG = " private static final String MENTION_AND_SCREEN_NAME = "@%s"; private static final String REGEX_AND_STRING = "(%s)"; private String getHTMLText(twitter4j.Status status) { if (status == null) { return null; } try { String textHTML = status.getText(); try { if (status.isRetweet()) { // fix RT truncated at the end if (textHTML.length() >= 140) { String textRT = status.getRetweetedStatus().getText(); int indexOf = textHTML.indexOf(textRT.substring(0, 70)); textHTML = textHTML.substring(0, indexOf) + textRT; } } } catch (Exception e) { MTLog.w(this, e, "Can't fix truncated RT '%s'! (using original text)", status.getText()); } for (twitter4j.URLEntity urlEntity : status.getURLEntities()) { textHTML = textHTML.replace(urlEntity.getURL(), getURL(urlEntity.getURL(), urlEntity.getDisplayURL())); } for (twitter4j.HashtagEntity hashtagEntity : status.getHashtagEntities()) { String hashtag = String.format(HASHTAG_AND_TAG, hashtagEntity.getText()); textHTML = textHTML.replace(hashtag, getURL(getHashtagURL(hashtagEntity.getText()), hashtag)); } for (twitter4j.UserMentionEntity userMentionEntity : status.getUserMentionEntities()) { String userMention = String.format(MENTION_AND_SCREEN_NAME, userMentionEntity.getScreenName()); textHTML = Pattern.compile(String.format(REGEX_AND_STRING, userMention), Pattern.CASE_INSENSITIVE).matcher(textHTML) .replaceAll(getURL(getAuthorProfileURL(userMentionEntity.getScreenName()), userMention)); } HashMap<String, HashSet<String>> urlToMediaUrls = new HashMap<String, HashSet<String>>(); for (twitter4j.MediaEntity exMediaEntity : status.getExtendedMediaEntities()) { if (!urlToMediaUrls.containsKey(exMediaEntity.getURL())) { urlToMediaUrls.put(exMediaEntity.getURL(), new HashSet<String>()); } urlToMediaUrls.get(exMediaEntity.getURL()).add(exMediaEntity.getMediaURLHttps()); } for (twitter4j.MediaEntity mediaEntity : status.getMediaEntities()) { if (!urlToMediaUrls.containsKey(mediaEntity.getURL())) { urlToMediaUrls.put(mediaEntity.getURL(), new HashSet<String>()); } urlToMediaUrls.get(mediaEntity.getURL()).add(mediaEntity.getMediaURLHttps()); } for (HashMap.Entry<String, HashSet<String>> entry : urlToMediaUrls.entrySet()) { StringBuilder sb = new StringBuilder(); for (String mediaUrl : entry.getValue()) { if (sb.length() > 0) { sb.append(StringUtils.SPACE_CAR); } sb.append(getURL(mediaUrl, mediaUrl)); } textHTML = textHTML.replace(entry.getKey(), sb.toString()); } return textHTML; } catch (Exception e) { MTLog.w(this, e, "Error while genereting HTML text for status '%s'!", status); return status.getText(); } } private static final String HREF_URL_AND_URL_AND_TEXT = "<A HREF=\"%s\">%s</A>"; private String getURL(String url, String text) { return String.format(HREF_URL_AND_URL_AND_TEXT, url, text); } private static final String WEB_URL_AND_SCREEN_NAME_AND_ID = "https://twitter.com/%s/status/%s"; private String getNewsWebURL(twitter4j.Status status) { return String.format(WEB_URL_AND_SCREEN_NAME_AND_ID, status.getUser().getScreenName(), status.getId()); // id or id_str ? } private static final String AUTHOR_PROFILE_URL_AND_SCREEN_NAME = "https://twitter.com/%s"; private String getAuthorProfileURL(twitter4j.User user) { return getAuthorProfileURL(user.getScreenName()); } private String getAuthorProfileURL(String userScreenName) { return String.format(AUTHOR_PROFILE_URL_AND_SCREEN_NAME, userScreenName); } private static final String HASHTAG_URL_AND_TAG = "https://twitter.com/hashtag/%s"; private String getHashtagURL(String hashtag) { return String.format(HASHTAG_URL_AND_TAG, hashtag); } private static class TwitterNewsDbHelper extends NewsProvider.NewsDbHelper { private static final String TAG = TwitterNewsDbHelper.class.getSimpleName(); @Override public String getLogTag() { return TAG; } /** * Override if multiple {@link TwitterNewsDbHelper} implementations in same app. */ protected static final String DB_NAME = "news_twitter.db"; /** * Override if multiple {@link TwitterNewsDbHelper} implementations in same app. */ protected static final String PREF_KEY_AGENCY_LAST_UPDATE_MS = "pTwitterNewsLastUpdate"; /** * Override if multiple {@link TwitterNewsDbHelper} implementations in same app. */ protected static final String PREF_KEY_AGENCY_LAST_UPDATE_LANG = "pTwitterNewsLastUpdateLang"; public static final String T_TWITTER_NEWS = NewsProvider.NewsDbHelper.T_NEWS; private static final String T_TWITTER_NEWS_SQL_CREATE = NewsProvider.NewsDbHelper.getSqlCreateBuilder(T_TWITTER_NEWS).build(); private static final String T_TWITTER_NEWS_SQL_DROP = SqlUtils.getSQLDropIfExistsQuery(T_TWITTER_NEWS); private static int dbVersion = -1; /** * Override if multiple {@link TwitterNewsDbHelper} in same app. */ public static int getDbVersion(Context context) { if (dbVersion < 0) { dbVersion = context.getResources().getInteger(R.integer.twitter_db_version); } return dbVersion; } private Context context; public TwitterNewsDbHelper(Context context) { this(context, DB_NAME, getDbVersion(context)); } public TwitterNewsDbHelper(Context context, String dbName, int dbVersion) { super(context, dbName, dbVersion); this.context = context; } @Override public String getDbName() { return DB_NAME; } @Override public void onCreateMT(SQLiteDatabase db) { initAllDbTables(db); } @Override public void onUpgradeMT(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(T_TWITTER_NEWS_SQL_DROP); PreferenceUtils.savePrefLcl(this.context, PREF_KEY_AGENCY_LAST_UPDATE_MS, 0l, true); PreferenceUtils.savePrefLcl(this.context, PREF_KEY_AGENCY_LAST_UPDATE_LANG, StringUtils.EMPTY, true); initAllDbTables(db); } private void initAllDbTables(SQLiteDatabase db) { db.execSQL(T_TWITTER_NEWS_SQL_CREATE); } } }
package org.sosy_lab.java_smt.solvers.yices2; import static com.google.common.base.CharMatcher.inRange; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.YICES_APP_TERM; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_parse_term; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_term_child; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_term_constructor; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_term_to_string; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_type_children; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_type_num_children; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_type_of_term; import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_type_to_string; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.io.IOException; import java.util.Map; import org.sosy_lab.common.Appender; import org.sosy_lab.common.Appenders; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.basicimpl.AbstractFormulaManager; public class Yices2FormulaManager extends AbstractFormulaManager<Integer, Integer, Long, Integer> { private static final CharMatcher LETTERS = inRange('a', 'z').or(inRange('A', 'Z')); private static final CharMatcher DIGITS = inRange('0', '9'); private static final CharMatcher ADDITIONAL_CHARS = CharMatcher.anyOf("~!@$%^&*_-+=<>.?/"); private static final CharMatcher VALID_CHARS = LETTERS.or(DIGITS).or(ADDITIONAL_CHARS); protected Yices2FormulaManager( Yices2FormulaCreator pFormulaCreator, Yices2UFManager pFunctionManager, Yices2BooleanFormulaManager pBooleanManager, Yices2IntegerFormulaManager pIntegerManager, Yices2RationalFormulaManager pRationalManager, Yices2BitvectorFormulaManager pBitvectorManager) { super( pFormulaCreator, pFunctionManager, pBooleanManager, pIntegerManager, pRationalManager, pBitvectorManager, null, null, null, null); } static Integer getYicesTerm(Formula pT) { return ((Yices2Formula) pT).getTerm(); } @Override public BooleanFormula parse(String pS) throws IllegalArgumentException { // TODO Might expect Yices input language instead of smt-lib2 notation return getFormulaCreator().encapsulateBoolean(yices_parse_term(pS)); } @Override public Appender dumpFormula(final Integer formula) { assert getFormulaCreator().getFormulaType(formula) == FormulaType.BooleanType : "Only BooleanFormulas may be dumped"; return new Appenders.AbstractAppender() { @Override public void appendTo(Appendable out) throws IOException { Map<String, Formula> varsAndUFs = extractVariablesAndUFs(getFormulaCreator().encapsulateWithTypeOf(formula)); for (Map.Entry<String, Formula> entry : varsAndUFs.entrySet()) { final int term = ((Yices2Formula) entry.getValue()).getTerm(); final int type; if (yices_term_constructor(term) == YICES_APP_TERM) { // Is an UF. Correct type is carried by first child. type = yices_type_of_term(yices_term_child(term, 0)); } else { type = yices_type_of_term(term); } final int[] types; if (yices_type_num_children(type) == 0) { types = new int[] {type}; } else { types = yices_type_children(type); // adds children types and then return type } if (types.length > 0) { out.append("(declare-fun "); out.append(quote(entry.getKey())); out.append(" ("); for (int i = 0; i < types.length - 1; i++) { out.append(getTypeRepr(types[i])); if (i + 1 < types.length - 1) { out.append(' '); } } out.append(") "); out.append(getTypeRepr(types[types.length - 1])); out.append(")\n"); } } // TODO fold formula to avoid exp. overhead out.append("(assert " + yices_term_to_string(formula) + ")"); } private String getTypeRepr(int type) { String typeRepr = yices_type_to_string(type); return typeRepr.substring(0, 1).toUpperCase() + typeRepr.substring(1); } }; } private static String quote(String str) { Preconditions.checkArgument(!Strings.isNullOrEmpty(str)); Preconditions.checkArgument(CharMatcher.anyOf("|\\").matchesNoneOf(str)); Preconditions.checkArgument(!SMTLIB2_KEYWORDS.contains(str)); if (VALID_CHARS.matchesAllOf(str) && !DIGITS.matches(str.charAt(0))) { // simple symbol return str; } else { // quoted symbol return "|" + str + "|"; } } }
package protocolsupport.protocol.packet.handler; import java.net.InetSocketAddress; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bukkit.Bukkit; import com.mojang.authlib.GameProfile; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import net.minecraft.server.v1_10_R1.ChatComponentText; import net.minecraft.server.v1_10_R1.EntityPlayer; import net.minecraft.server.v1_10_R1.IChatBaseComponent; import net.minecraft.server.v1_10_R1.ITickable; import net.minecraft.server.v1_10_R1.LoginListener; import net.minecraft.server.v1_10_R1.MinecraftServer; import net.minecraft.server.v1_10_R1.NetworkManager; import net.minecraft.server.v1_10_R1.PacketListenerPlayIn; import net.minecraft.server.v1_10_R1.PacketLoginInEncryptionBegin; import net.minecraft.server.v1_10_R1.PacketLoginInStart; import net.minecraft.server.v1_10_R1.PacketLoginOutSuccess; import net.minecraft.server.v1_10_R1.PacketPlayInAbilities; import net.minecraft.server.v1_10_R1.PacketPlayInArmAnimation; import net.minecraft.server.v1_10_R1.PacketPlayInBlockDig; import net.minecraft.server.v1_10_R1.PacketPlayInBlockPlace; import net.minecraft.server.v1_10_R1.PacketPlayInBoatMove; import net.minecraft.server.v1_10_R1.PacketPlayInChat; import net.minecraft.server.v1_10_R1.PacketPlayInClientCommand; import net.minecraft.server.v1_10_R1.PacketPlayInCloseWindow; import net.minecraft.server.v1_10_R1.PacketPlayInCustomPayload; import net.minecraft.server.v1_10_R1.PacketPlayInEnchantItem; import net.minecraft.server.v1_10_R1.PacketPlayInEntityAction; import net.minecraft.server.v1_10_R1.PacketPlayInFlying; import net.minecraft.server.v1_10_R1.PacketPlayInHeldItemSlot; import net.minecraft.server.v1_10_R1.PacketPlayInKeepAlive; import net.minecraft.server.v1_10_R1.PacketPlayInResourcePackStatus; import net.minecraft.server.v1_10_R1.PacketPlayInSetCreativeSlot; import net.minecraft.server.v1_10_R1.PacketPlayInSettings; import net.minecraft.server.v1_10_R1.PacketPlayInSpectate; import net.minecraft.server.v1_10_R1.PacketPlayInSteerVehicle; import net.minecraft.server.v1_10_R1.PacketPlayInTabComplete; import net.minecraft.server.v1_10_R1.PacketPlayInTeleportAccept; import net.minecraft.server.v1_10_R1.PacketPlayInTransaction; import net.minecraft.server.v1_10_R1.PacketPlayInUpdateSign; import net.minecraft.server.v1_10_R1.PacketPlayInUseEntity; import net.minecraft.server.v1_10_R1.PacketPlayInUseItem; import net.minecraft.server.v1_10_R1.PacketPlayInVehicleMove; import net.minecraft.server.v1_10_R1.PacketPlayInWindowClick; import net.minecraft.server.v1_10_R1.PacketPlayOutKeepAlive; import net.minecraft.server.v1_10_R1.PacketPlayOutKickDisconnect; import protocolsupport.api.events.PlayerLoginFinishEvent; import protocolsupport.utils.Utils; public class LoginListenerPlay extends LoginListener implements PacketListenerPlayIn, ITickable { protected static final Logger logger = LogManager.getLogger(); protected static final MinecraftServer server = Utils.getServer(); private final GameProfile profile; protected boolean ready; public LoginListenerPlay(NetworkManager networkmanager, GameProfile profile, String hostname) { super(server, networkmanager); this.profile = profile; this.hostname = hostname; } public void finishLogin() { networkManager.sendPacket(new PacketLoginOutSuccess(profile)); PlayerLoginFinishEvent event = new PlayerLoginFinishEvent((InetSocketAddress) networkManager.getSocketAddress(), profile.getName(), profile.getId()); Bukkit.getPluginManager().callEvent(event); if (event.isLoginDenied()) { disconnect(event.getDenyLoginMessage()); return; } ready = true; } protected int keepAliveTicks = 0; @Override public void E_() { if (keepAliveTicks++ % 20 == 0) { networkManager.sendPacket(new PacketPlayOutKeepAlive(0)); } if (ready) { ready = false; b(); } } @Override public void b() { EntityPlayer loginplayer = server.getPlayerList().attemptLogin(this, profile, hostname); if (loginplayer != null) { server.getPlayerList().a(this.networkManager, loginplayer); ready = false; } } @Override public void a(final IChatBaseComponent ichatbasecomponent) { logger.info(d() + " lost connection: " + ichatbasecomponent.getText()); } @Override public String d() { return profile + " (" + networkManager.getSocketAddress() + ")"; } @SuppressWarnings("unchecked") @Override public void disconnect(final String s) { try { logger.info("Disconnecting " + d() + ": " + s); final ChatComponentText chatcomponenttext = new ChatComponentText(s); networkManager.sendPacket(new PacketPlayOutKickDisconnect(chatcomponenttext), new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { networkManager.close(chatcomponenttext); } }); } catch (Exception exception) { logger.error("Error whilst disconnecting player", exception); } } @Override public void a(final PacketLoginInStart packetlogininstart) { } @Override public void a(final PacketLoginInEncryptionBegin packetlogininencryptionbegin) { } @Override public void a(PacketPlayInArmAnimation p0) { } @Override public void a(PacketPlayInChat p0) { } @Override public void a(PacketPlayInTabComplete p0) { } @Override public void a(PacketPlayInClientCommand p0) { } @Override public void a(PacketPlayInSettings p0) { } @Override public void a(PacketPlayInTransaction p0) { } @Override public void a(PacketPlayInEnchantItem p0) { } @Override public void a(PacketPlayInWindowClick p0) { } @Override public void a(PacketPlayInCloseWindow p0) { } @Override public void a(PacketPlayInCustomPayload p0) { } @Override public void a(PacketPlayInUseEntity p0) { } @Override public void a(PacketPlayInKeepAlive p0) { } @Override public void a(PacketPlayInFlying p0) { } @Override public void a(PacketPlayInAbilities p0) { } @Override public void a(PacketPlayInBlockDig p0) { } @Override public void a(PacketPlayInEntityAction p0) { } @Override public void a(PacketPlayInSteerVehicle p0) { } @Override public void a(PacketPlayInHeldItemSlot p0) { } @Override public void a(PacketPlayInSetCreativeSlot p0) { } @Override public void a(PacketPlayInUpdateSign p0) { } @Override public void a(PacketPlayInUseItem p0) { } @Override public void a(PacketPlayInBlockPlace p0) { } @Override public void a(PacketPlayInSpectate p0) { } @Override public void a(PacketPlayInResourcePackStatus p0) { } @Override public void a(PacketPlayInBoatMove p0) { } @Override public void a(PacketPlayInVehicleMove p0) { } @Override public void a(PacketPlayInTeleportAccept p0) { } }
package kieker.tpan.logReader; import java.io.Serializable; import kieker.common.logReader.AbstractKiekerMonitoringLogReader; import java.util.Hashtable; import javax.jms.JMSException; import javax.naming.Context; import javax.naming.InitialContext; import javax.jms.ConnectionFactory; import javax.jms.Connection; import javax.jms.Destination; import javax.jms.Message; import javax.jms.Session; import javax.jms.MessageConsumer; import javax.jms.MessageFormatException; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import javax.jms.TextMessage; import kieker.common.logReader.LogReaderExecutionException; import kieker.tpmon.annotation.TpmonInternal; import kieker.tpmon.monitoringRecord.AbstractKiekerMonitoringRecord; import kieker.tpmon.writer.jmsAsync.MonitoringRecordTypeClassnameMapping; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Reads tpmon messages from a (remote or local) JMS queue and processes them in tpan. * * * @author Andre van Hoorn, Matthias Rohr * History * 2009-07-01 (AvH) Initial version * 2009-07-25 (MR) */ public class JMSReader extends AbstractKiekerMonitoringLogReader { private static final Log log = LogFactory.getLog(JMSReader.class); private String jmsProviderUrl = null; private String jmsDestination = null; public JMSReader(String jmsProviderUrl, String jmsDestination) { initInstanceFromArgs(jmsProviderUrl, jmsDestination); } /** Constructor for JMSReader. Requires a subsequent call to the init * method in order to specify the input directory using the parameter * @a inputDirName. */ public JMSReader(){ } /** Valid key/value pair: inputDirName=INPUTDIRECTORY | numWorkers=XX */ @TpmonInternal() public void init(String initString) throws IllegalArgumentException { super.initVarsFromInitString(initString); String jmsProviderUrlP = this.getInitProperty("jmsProviderUrl", null); String jmsDestinationP = this.getInitProperty("jmsDestination", null); initInstanceFromArgs(jmsProviderUrlP, jmsDestinationP); } private void initInstanceFromArgs(final String jmsProviderUrl, final String jmsDestination) throws IllegalArgumentException { if (jmsProviderUrl == null || jmsProviderUrl.equals("") || jmsDestination == null || jmsDestination.equals("")) { throw new IllegalArgumentException("JMSReader has not sufficient parameters. jmsProviderUrl or jmsDestination is null"); } this.jmsProviderUrl = jmsProviderUrl; this.jmsDestination = jmsDestination; } /** * A call to this method is a blocking call. */ public boolean execute() throws LogReaderExecutionException { boolean retVal = false; try { Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.exolab.jms.jndi.InitialContextFactory"); //properties.put(Context.PROVIDER_URL, "tcp://pc-rohr.informatik.uni-oldenburg.de:3035/"); // JMS initialization properties.put(Context.PROVIDER_URL, jmsProviderUrl); Context context = new InitialContext(properties); ConnectionFactory factory = (ConnectionFactory) context.lookup("ConnectionFactory"); Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = (Destination) context.lookup(jmsDestination); log.info("\n\n***\nListening to destination:" + destination + " at " + jmsProviderUrl + " !\n***\n\n"); MessageConsumer receiver = session.createConsumer(destination); receiver.setMessageListener(new MessageListener() { // the MessageListener will execute onMessage each time a message comes in public void onMessage(Message jmsMessage) { if (jmsMessage instanceof TextMessage) { TextMessage text = (TextMessage) jmsMessage; log.info("Received text message: " + text); } else { ObjectMessage om = (ObjectMessage) jmsMessage; //System.out.println("Received object message: " + om.toString()); try { Serializable omo = om.getObject(); if (omo instanceof AbstractKiekerMonitoringRecord) { AbstractKiekerMonitoringRecord rec = (AbstractKiekerMonitoringRecord) omo; Class<? extends AbstractKiekerMonitoringRecord> clazz = fetchClassForRecordTypeId(rec.getRecordTypeId()); if (clazz == null) { // TODO: we could retry it in a couple of seconds log.error("Found no mapping for record type id " + rec.getRecordTypeId()); } else { //log.info("New monitoring record of type " + clazz.getName() + " (id:" + rec.getRecordTypeId() + ")"); deliverRecordToConsumers(rec); } } else if (omo instanceof MonitoringRecordTypeClassnameMapping) { MonitoringRecordTypeClassnameMapping m = (MonitoringRecordTypeClassnameMapping) omo; registerRecordTypeIdMapping(m.typeId, m.classname); log.info("Received mapping " + m.typeId + "/" + m.classname); } else { log.info("Unknown type of message " + om); } } catch (MessageFormatException em) { log.fatal("MessageFormatException:", em); } catch (JMSException ex) { log.fatal("JMSException ", ex); } catch (LogReaderExecutionException ex) { log.error("LogReaderExecutionException", ex); } catch (Exception ex) { log.error("Exception", ex); } } } }); // start the connection to enable message delivery connection.start(); System.out.println("JMSTestListener1 is started and waits for incomming monitoring events!"); final Object blockingObj = new Object(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { synchronized (blockingObj) { blockingObj.notifyAll(); } } })); synchronized (blockingObj) { blockingObj.wait(); } log.info("Woke up by shutdown hook"); } catch (Exception ex) { System.out.println("" + JMSReader.class.getName() + " " + ex.getMessage()); ex.printStackTrace(); retVal = false; } finally { super.terminate(); } return retVal; } }
package com.facebook.litho.widget; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentView; import com.facebook.litho.testing.ComponentTestHelper; import com.facebook.litho.testing.testrunner.ComponentsTestRunner; import com.facebook.litho.testing.ComponentsRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; /** * Tests {@link EditText} component. */ @RunWith(ComponentsTestRunner.class) public class EditTextSpecTest { @Rule public ComponentsRule mComponentsRule = new ComponentsRule(); private static final String TEXT = "Hello Components"; @Test public void testEditTextWithText() { final ComponentContext c = mComponentsRule.getContext(); final ComponentView componentView = ComponentTestHelper.mountComponent( EditText.create(c) .textChangedEventHandler(null) .textSizePx(10) .text(TEXT)); final android.widget.EditText editText = (android.widget.EditText) componentView.getChildAt(0); assertThat(editText.getText().toString()).isEqualTo(TEXT); assertThat(editText.getTextSize()).isEqualTo(10); } }
package eu.rethink.globalregistry.tests; import static org.junit.Assert.*; import org.junit.Test; import eu.rethink.globalregistry.util.XSDDateTime; public class XSDDateTimeTest { //valid public String validXSD1 = "2017-02-07T12:13:14+01:00"; public String validXSD2 = "2017-02-07T12:13:14Z"; //invalid public String invalidXSD1 = "2017-02-07T25:13:14+01:00"; public String invalidXSD2 = "42017-02-07T12:13:14+01:00"; public String invalidXSD3 = "2017-02-07T12:13:61+01:00"; public String invalidXSD4 = "2017-02-07Tl2:13:14+01:00"; public String invalidXSD5 = "2017-02-07T12:13:14ZZ"; @Test public void XSDDateTimeValidationTest() { assertTrue(XSDDateTime.validateXSDDateTime(validXSD1)); assertTrue(XSDDateTime.validateXSDDateTime(validXSD2)); //assertFalse(XSDDateTime.validateXSDDateTime(invalidXSD1)); assertFalse(XSDDateTime.validateXSDDateTime(invalidXSD2)); //assertFalse(XSDDateTime.validateXSDDateTime(invalidXSD3)); assertFalse(XSDDateTime.validateXSDDateTime(invalidXSD4)); assertFalse(XSDDateTime.validateXSDDateTime(invalidXSD5)); } }
package org.epics.vtype; import java.util.List; import org.epics.util.array.ListDouble; import org.epics.util.array.ListInt; /** * * @author carcassi */ class IVIntArray extends IVNumeric implements VIntArray { private final ListInt data; private final ListInt sizes; private final List<ArrayDimensionDisplay> dimensionDisplay; public IVIntArray(ListInt data, ListInt sizes, Alarm alarm, Time time, Display display) { this(data, sizes, null, alarm, time, display); } public IVIntArray(ListInt data, ListInt sizes, List<ArrayDimensionDisplay> dimDisplay, Alarm alarm, Time time, Display display) { super(alarm, time, display); this.sizes = sizes; this.data = data; if (dimDisplay == null) { this.dimensionDisplay = ValueUtil.defaultArrayDisplay(sizes); } else { this.dimensionDisplay = dimDisplay; } } @Override public ListInt getSizes() { return sizes; } @Override public ListInt getData() { return data; } @Override public String toString() { return VTypeToString.toString(this); } @Override public List<ArrayDimensionDisplay> getDimensionDisplay() { return dimensionDisplay; } }
package io.github.classgraph.issues.issue80; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import io.github.classgraph.ClassGraph; import io.github.classgraph.ScanResult; public class Issue80Test { @Test public void issue80() { try (ScanResult scanResult = new ClassGraph().enableSystemPackages().enableClassInfo().scan()) { assertThat(scanResult.getAllStandardClasses().getNames()).contains("java.util.ArrayList"); } } }
package no.stelar7.api.l4j8.tests.staticdata; import no.stelar7.api.l4j8.basic.constants.api.*; import no.stelar7.api.l4j8.basic.constants.flags.*; import no.stelar7.api.l4j8.impl.*; import no.stelar7.api.l4j8.pojo.staticdata.champion.*; import no.stelar7.api.l4j8.pojo.staticdata.item.*; import no.stelar7.api.l4j8.pojo.staticdata.language.LanguageStrings; import no.stelar7.api.l4j8.pojo.staticdata.map.MapData; import no.stelar7.api.l4j8.pojo.staticdata.mastery.*; import no.stelar7.api.l4j8.pojo.staticdata.profileicon.ProfileIconData; import no.stelar7.api.l4j8.pojo.staticdata.realm.Realm; import no.stelar7.api.l4j8.pojo.staticdata.rune.*; import no.stelar7.api.l4j8.pojo.staticdata.summonerspell.*; import no.stelar7.api.l4j8.tests.SecretFile; import org.junit.*; import java.util.*; public class StaticTest { final L4J8 l4j8 = new L4J8(SecretFile.CREDS); StaticAPI api = l4j8.getStaticAPI(); Optional<String> version = Optional.empty(); Optional<String> locale = Optional.empty(); @Test public void testChampionList() { Optional<EnumSet<ChampDataFlags>> dataFlags = Optional.of(EnumSet.of(ChampDataFlags.ALL)); Optional<StaticChampionList> list = api.getChampions(Platform.EUW1, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); Assert.assertTrue("less than 100?", list.get().getData().size() > 100); } @Test public void testChampionSingle() { Optional<EnumSet<ChampDataFlags>> dataFlags = Optional.of(EnumSet.of(ChampDataFlags.ALL)); Optional<StaticChampion> list = api.getChampion(Platform.EUW1, Constants.TEST_CHAMPION_IDS[0], dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); Assert.assertTrue("ok?", list.get().getId() == Constants.TEST_CHAMPION_IDS[0]); } @Test public void testItemList() { Optional<EnumSet<ItemDataFlags>> dataFlags = Optional.of(EnumSet.of(ItemDataFlags.ALL)); Optional<ItemList> list = api.getItems(Platform.EUW1, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); Assert.assertTrue("less than 100?", list.get().getData().size() > 100); } @Test public void testItemSingle() { Optional<EnumSet<ItemDataFlags>> dataFlags = Optional.of(EnumSet.of(ItemDataFlags.ALL)); Optional<Item> list = api.getItem(Platform.EUW1, 1018, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); Assert.assertTrue("ok?", list.get().getId() == 1018); } @Test public void testLanguageStrings() { Optional<LanguageStrings> strings = api.getLanguageStrings(Platform.EUW1, version, locale); Assert.assertTrue("no data?", strings.isPresent()); } @Test public void testLanguages() { Optional<List<String>> strings = api.getLanguages(Platform.EUW1); Assert.assertTrue("no data?", strings.isPresent()); } @Test public void testMaps() { Optional<MapData> data = api.getMaps(Platform.EUW1, version, locale); Assert.assertTrue("no data?", data.isPresent()); } @Test public void testMasteryList() { Optional<EnumSet<MasteryDataFlags>> dataFlags = Optional.of(EnumSet.of(MasteryDataFlags.ALL)); Optional<MasteryList> list = api.getMasteries(Platform.EUW1, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); } @Test public void testMasterySingle() { Optional<EnumSet<MasteryDataFlags>> dataFlags = Optional.of(EnumSet.of(MasteryDataFlags.ALL)); Optional<Mastery> list = api.getMastery(Platform.EUW1, 6131, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); Assert.assertTrue("ok?", list.get().getId() == 6131); } @Test public void testProfileIcons() { Optional<ProfileIconData> data = api.getProfileIcons(Platform.EUW1, Optional.empty(), Optional.empty()); Assert.assertTrue("no data?", data.isPresent()); } @Test public void testRealms() { Optional<Realm> data = api.getRealm(Platform.EUW1); Assert.assertTrue("no data?", data.isPresent()); } @Test public void testRuneList() { Optional<EnumSet<RuneDataFlags>> dataFlags = Optional.of(EnumSet.of(RuneDataFlags.ALL)); Optional<StaticRuneList> list = api.getRunes(Platform.EUW1, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); } @Test public void testRuneSingle() { Optional<EnumSet<RuneDataFlags>> dataFlags = Optional.of(EnumSet.of(RuneDataFlags.ALL)); Optional<StaticRune> rune = api.getRune(Platform.EUW1, 5023, dataFlags, version, locale); Assert.assertTrue("no data?", rune.isPresent()); Assert.assertTrue("missing id?", rune.get().getId() == 5023); Assert.assertTrue("missing stats?", rune.get().getStats() != null); Assert.assertTrue("missing desc?", rune.get().getDescription() != null); Assert.assertTrue("missing tags?", rune.get().getTags() != null); Assert.assertTrue("missing image?", rune.get().getImage() != null); Assert.assertTrue("missing sandesc?", rune.get().getSanitizedDescription() != null); Assert.assertTrue("missing rune?", rune.get().getRune() != null); Assert.assertTrue("missing name?", rune.get().getName() != null); } @Test public void testSummonerSpellList() { Optional<EnumSet<SpellDataFlags>> dataFlags = Optional.of(EnumSet.of(SpellDataFlags.ALL)); Optional<StaticSummonerSpellList> list = api.getSummonerSpells(Platform.EUW1, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); } @Test public void testSummonerSpellSingle() { Optional<EnumSet<SpellDataFlags>> dataFlags = Optional.of(EnumSet.of(SpellDataFlags.ALL)); Optional<StaticSummonerSpell> list = api.getSummonerSpell(Platform.EUW1, 21, dataFlags, version, locale); Assert.assertTrue("no data?", list.isPresent()); Assert.assertTrue("ok?", list.get().getId() == 21); } @Test public void testVersions() { Optional<List<String>> data = api.getVersions(Platform.EUW1); Assert.assertTrue("no data?", data.isPresent()); } }
package org.basex.test.query.advanced; import static org.junit.Assert.*; import java.io.IOException; import org.basex.core.Context; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.func.FunDef; import org.basex.query.item.AtomType; import org.basex.query.item.SeqType; import org.basex.query.util.Err; abstract class AdvancedQueryTest { /** Database context. */ protected static final Context CTX = new Context(); /** * Runs the specified query. * @param qu query * @return result * @throws QueryException database exception */ protected static String query(final String qu) throws QueryException { final QueryProcessor qp = new QueryProcessor(qu, CTX); try { return qp.execute().toString().replaceAll("(\\r|\\n) *", ""); } finally { try { qp.close(); } catch(final IOException e) { } } } /** * Checks if a query yields the specified string. * @param query query to be run * @param result query result * @throws QueryException database exception */ protected static void query(final String query, final String result) throws QueryException { assertEquals(result, query(query)); } /** * Checks if a query yields the specified error code. * @param query query to be run * @param result query result * @throws QueryException database exception */ protected static void contains(final String query, final String result) throws QueryException { assertContains(query(query), result); } /** * Checks if a query yields the specified error code. * @param query query to be run * @param error expected error */ protected static void error(final String query, final Err... error) { try { query(query); fail("[" + error[0] + "] expected for query: " + query); } catch(final QueryException ex) { final String msg = ex.getMessage(); boolean found = false; for(final Err e : error) found |= msg.contains(e.code()); if(!found) { fail("'" + error[0].code() + "' not contained in '" + msg + "'."); } } } /** * Checks if a string is contained in another string. * @param str string * @param sub sub string */ private static void assertContains(final String str, final String sub) { if(!str.contains(sub)) { fail("'" + sub + "' not contained in '" + str + "'."); } } /** * Checks if the specified function correctly handles its argument types, * and returns the function name. * @param def function definition * types are supported. * @return function name */ protected String check(final FunDef def) { final String desc = def.toString(); final String name = desc.replaceAll("\\(.*", ""); // test too few, too many, and wrong argument types for(int al = Math.max(def.min - 1, 0); al <= def.max + 1; al++) { final boolean in = al >= def.min && al <= def.max; final StringBuilder qu = new StringBuilder(name + "("); int any = 0; for(int a = 0; a < al; a++) { if(a != 0) qu.append(", "); if(in) { // test arguments if(def.args[a].type == AtomType.STR) { qu.append("1"); } else { // any type (skip test) qu.append("'X'"); if(SeqType.STR.instance(def.args[a])) any++; } } else { // test wrong number of arguments qu.append("'x'"); } } // skip test if all types are arbitrary if((def.min > 0 || al != 0) && (any == 0 || any != al)) { final String query = qu.append(")").toString(); if(in) error(query, Err.XPTYPE, Err.NODBCTX); else error(query, Err.XPARGS); } } return name; } /** * Returns serialization parameters. * @param arg serialization arguments * @return parameter string */ protected static String serialParams(final String arg) { return "<serialization-parameters " + "xmlns='http: "</serialization-parameters>"; } }
package org.thymoljs.thymol.test.selenium; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.AfterClass; import org.junit.BeforeClass; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.thymoljs.thymol.test.selenium.webdriver.ChromeFactory; import org.thymoljs.thymol.test.selenium.webdriver.FirefoxFactory; import org.thymoljs.thymol.test.selenium.webdriver.InternetExplorerFactory; import org.thymoljs.thymol.test.selenium.webdriver.WebDriverFactory; public class SeleniumCases { protected static WebDriverFactory driverFactory = null; protected static WebDriver driver = null; protected static URIGetter getter; public static void setup(URIGetter g) { getter = g; String webDriverProperty = System.getProperty( "webDriver" ); System.out.println( " webDriver is: " + webDriverProperty); if( webDriverProperty == null || "firefox".equals( webDriverProperty ) ) { driverFactory = new FirefoxFactory(); } else if( "chrome".equals( webDriverProperty ) ) { driverFactory = new ChromeFactory(); } else if( "internetExplorer".equals( webDriverProperty ) ) { driverFactory = new InternetExplorerFactory(); } } public SeleniumCases() { super(); } public void localise(String path) { getter.localise(path); } public String getURI(String path) { return getter.getURI(path); } @BeforeClass public static void startUp() { driver = driverFactory.create(); } @AfterClass public static void shutDown() { driver = driverFactory.destroy( driver ); } private static class AnnotatedWebElement extends RemoteWebElement { String errorMessage = null; AnnotatedWebElement(String errorMessage) { this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } } private class PageResponse implements ExpectedCondition<WebElement> { ResultMode mode = null; PageResponse(ResultMode modeValue) { super(); mode = modeValue; } @Override public WebElement apply(WebDriver d) { WebElement e = null; Alert a = null; WebDriver.TargetLocator locator = d.switchTo(); try { switch (mode) { case HTML: case TEXT: { e = locator.activeElement(); break; } case ALERT: { a = locator.alert(); if (a != null) { e = handleAlert(a); } break; } } } catch (UnhandledAlertException uae) { String alertText = uae.getAlertText(); if (alertText == null) { alertText = "cannot read alert text!"; } e = new AnnotatedWebElement(alertText); try { a = locator.alert(); if (a != null) { e = handleAlert(a); } } catch (NoAlertPresentException nape) { System.out.println("NoAlertPresentException2!"); } } catch (NoAlertPresentException nape) { e = d.findElement(By.tagName("body")); } return e; } } // TODO need to add a control parameter that says we are expecting an alert or a normal page // We can no longer do the "one size fits all" solution because the firefox driver is broken. // There is a work-around but it's very slow because it means waiting for a 500 server error when there is no alert to dismiss. // This takes 2 seconds and there doesn't seem to be any way of changing it. // It's a real shame that it's firefox (v30 and up) that screwed up the simple solution public WebElement getResultBody( String relative, ResultMode mode ) { String location = ( new StringBuilder( getURI("") ) ).append( relative ).toString(); try { driver.get( location ); } catch(UnhandledAlertException uae) { uae.printStackTrace(); try { Alert alert = driver.switchTo().alert(); alert.dismiss(); } catch(NoAlertPresentException nape) { System.out.println("NoAlertPresentException1!"); } driver.get( location ); } WebElement body = ( new WebDriverWait( driver, 1 ) ).until( new PageResponse(mode) ); return body; } private WebElement handleAlert(Alert a) throws NoAlertPresentException { WebElement e = null; String alertText = a.getText(); if( alertText == null ) { alertText = "cannot read alert text!"; } e = new AnnotatedWebElement(alertText); a.dismiss(); return e; } public String getResult( String relative, ResultMode mode ) { String result = null; WebElement body = getResultBody( relative, mode ); if( body != null ) { switch( mode ) { case HTML: { result = body.getAttribute( "innerHTML" ); break; } case TEXT: { result = body.getText(); break; } case ALERT: { if( body instanceof AnnotatedWebElement ) { result = ((AnnotatedWebElement)body).getErrorMessage(); } else if( body instanceof RemoteWebElement ) { result = body.getAttribute( "innerHTML" ); } else { result = "**Result Processing Error incorrect type**"; } break; } } } else { result = "**Result Processing Error no result**"; } return result; } private static final String SORT_SELECTOR_START = "<span id=\"sort\">"; private static final String SORT_SELECTOR_END = "</span>"; private String replaceSortedFields(String result) { int sortSpan = result.indexOf( SORT_SELECTOR_START ); if( sortSpan > -1 ) { String part = result.substring( sortSpan, result.indexOf( SORT_SELECTOR_END, sortSpan ) + SORT_SELECTOR_END.length() ); String extract = result.substring( sortSpan + SORT_SELECTOR_START.length(), result.indexOf( SORT_SELECTOR_END, sortSpan ) ) ; String[] parts = extract.split( "," ); Arrays.sort( parts ); StringBuilder sb = new StringBuilder(); sb.append( SORT_SELECTOR_START ); boolean started = false; for( String p: parts ) { if( started ) { sb.append( "," ); } sb.append( p ); started = true; } sb.append( SORT_SELECTOR_END ); String xp = sb.toString(); result = result.replace( part, xp ); } return result; } public String clean(String s1) { Pattern p = Pattern.compile(";jsessionid=[^\"^?]*"); Matcher m = p.matcher(s1); s1 = m.replaceAll(""); s1 = removeComments(s1); s1 = s1.replaceAll("\\n", ""); s1 = s1.replaceAll("\\t", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll(" ", " "); s1 = s1.replaceAll("> <", "><"); s1 = s1.replaceAll(" </", "</"); s1 = replaceSortedFields(s1); return s1; } private String removeComments(String x) { String y = x; int startComment = -1; do { startComment = y.indexOf("<! if( startComment >= 0 ) { int endComment = y.indexOf("-->",startComment); if( endComment >= 0 ) { StringBuilder sb = new StringBuilder(); sb = sb.append(y.substring(0, startComment)); sb = sb.append(y.substring(endComment+3)); y = sb.toString(); } } } while(startComment>=0); return y; } public boolean expectThymeleafResult() { boolean result = false; if( getter.getClass().isAssignableFrom( FailSafeEnv.class ) ) { result = true; } return result; } public boolean expectThymolResult() { boolean result = false; if( getter.getClass().isAssignableFrom( SureFireEnv.class ) ) { result = true; } return result; } }
package org.thymoljs.thymol.test.selenium; import org.thymoljs.thymol.test.selenium.cases.AggregatesCases; import org.thymoljs.thymol.test.selenium.cases.AppendPrependCases; import org.thymoljs.thymol.test.selenium.cases.ArraysCases; import org.thymoljs.thymol.test.selenium.cases.AttrCases; import org.thymoljs.thymol.test.selenium.cases.BoolsCases; import org.thymoljs.thymol.test.selenium.cases.CalendarsCases; import org.thymoljs.thymol.test.selenium.cases.DatesCases; import org.thymoljs.thymol.test.selenium.cases.DebugCases; import org.thymoljs.thymol.test.selenium.cases.DomSelectorCases; import org.thymoljs.thymol.test.selenium.cases.EachCases; import org.thymoljs.thymol.test.selenium.cases.ExprCases; import org.thymoljs.thymol.test.selenium.cases.ExpressionCases; import org.thymoljs.thymol.test.selenium.cases.ExpressionDerivedCases; import org.thymoljs.thymol.test.selenium.cases.IdsCases; import org.thymoljs.thymol.test.selenium.cases.IfCases; import org.thymoljs.thymol.test.selenium.cases.IncludeCases; import org.thymoljs.thymol.test.selenium.cases.InlineCases; import org.thymoljs.thymol.test.selenium.cases.LinkCases; import org.thymoljs.thymol.test.selenium.cases.ClassicMessageCases; import org.thymoljs.thymol.test.selenium.cases.ListsCases; import org.thymoljs.thymol.test.selenium.cases.MapsCases; import org.thymoljs.thymol.test.selenium.cases.MessagesCases; import org.thymoljs.thymol.test.selenium.cases.ObjectCases; import org.thymoljs.thymol.test.selenium.cases.ObjectsCases; import org.thymoljs.thymol.test.selenium.cases.ParamsCases; import org.thymoljs.thymol.test.selenium.cases.RefCases; import org.thymoljs.thymol.test.selenium.cases.RemoveCases; import org.thymoljs.thymol.test.selenium.cases.ReplaceCases; import org.thymoljs.thymol.test.selenium.cases.SetsCases; import org.thymoljs.thymol.test.selenium.cases.StringsCases; import org.thymoljs.thymol.test.selenium.cases.SwitchCases; import org.thymoljs.thymol.test.selenium.cases.WithCases; import org.thymoljs.thymol.test.selenium.issues.IssuesCases; import org.thymoljs.thymol.test.selenium.thymol20.Thymol20Cases; import org.thymoljs.thymol.test.selenium.v21cases.AssertCases21; import org.thymoljs.thymol.test.selenium.v21cases.BlockCases21; import org.thymoljs.thymol.test.selenium.v21cases.DomSelectorCases21; import org.thymoljs.thymol.test.selenium.v21cases.ExpressionCases21; import org.thymoljs.thymol.test.selenium.v21cases.IncludeCases21; import org.thymoljs.thymol.test.selenium.v21cases.LinkCases21; import org.thymoljs.thymol.test.selenium.v21cases.LiteralSubstCases21; import org.thymoljs.thymol.test.selenium.v21cases.ParsingCases21; import org.thymoljs.thymol.test.selenium.v21cases.RemoveCases21; import org.thymoljs.thymol.test.selenium.v21cases.ReplaceCases21; import org.thymoljs.thymol.test.selenium.v21cases.SyntaxCases21; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ AppendPrependCases.class, AttrCases.class, DomSelectorCases.class, EachCases.class, ExpressionCases.class, IfCases.class, IncludeCases.class, InlineCases.class, LinkCases.class, MessagesCases.class, ObjectCases.class, RemoveCases.class, ReplaceCases.class, SwitchCases.class, WithCases.class, ArraysCases.class, AggregatesCases.class, BoolsCases.class, CalendarsCases.class, DatesCases.class, DebugCases.class, ExprCases.class, ExpressionDerivedCases.class, IdsCases.class, ClassicMessageCases.class, ListsCases.class, MapsCases.class, ParamsCases.class, RefCases.class, ObjectsCases.class, SetsCases.class, StringsCases.class, Thymol20Cases.class, AssertCases21.class, BlockCases21.class, DomSelectorCases21.class, ExpressionCases21.class, IncludeCases21.class, LinkCases21.class, LiteralSubstCases21.class, ParsingCases21.class, RemoveCases21.class, ReplaceCases21.class, SyntaxCases21.class, IssuesCases.class }) public class SeleniumSuite { }
package jodd.lagarto; import jodd.log.Log; import jodd.util.StringPool; import jodd.util.StringUtil; import java.io.IOException; import java.nio.CharBuffer; /** * Lagarto HTML/XML parser engine. Usage consist of two steps: * <li>{@link #initialize(java.nio.CharBuffer) initalization} with provided content * <li>actual {@link #parse(TagVisitor) parsing} the content */ public abstract class LagartoParserEngine { private static final Log log = Log.getLogger(LagartoParserEngine.class); private static final String HTML_QUOTE = "&quot;"; private CharSequence input; private LagartoLexer lexer; private ParsedTag tag; private TagVisitor visitor; private Token lastToken = Token.UNKNOWN; private CharSequence lastText; private boolean buffering; private int buffTextStart; private int buffTextEnd; /** * Initializes parser engine by providing the content. */ protected void initialize(CharBuffer input) { this.input = input; this.lexer = new LagartoLexer(input); this.tag = new ParsedTag(input); this.buffering = false; this.buffTextStart = 0; this.buffTextEnd = 0; this.lastText = null; this.lastToken = Token.UNKNOWN; } /** * Returns Lagarto lexer. */ public LagartoLexer getLexer() { return lexer; } protected boolean enableConditionalComments = true; protected boolean calculatePosition; public boolean isEnableConditionalComments() { return enableConditionalComments; } /** * Enables detection of IE conditional comments. If not enabled, * downlevel-hidden cond. comments will be treated as regular comment, * while revealed cond. comments will be treated as an error. */ public void setEnableConditionalComments(boolean enableConditionalComments) { this.enableConditionalComments = enableConditionalComments; } /** * Resolves current position on {@link #error(String) parsing errors} * and other occasions. Note: this makes processing SLOW! * JFlex may be used to track current line and row, but that brings * overhead, and can't be easily disabled. By enabling this property, * position will be calculated manually only on errors. */ public void setCalculatePosition(boolean calculatePosition) { this.calculatePosition = calculatePosition; } public boolean isCalculatePosition() { return calculatePosition; } protected boolean parseSpecialTagsAsCdata = true; /** * Specifies if special tags should be parsed as CDATA block. */ public void setParseSpecialTagsAsCdata(boolean parseSpecialTagsAsCdata) { this.parseSpecialTagsAsCdata = parseSpecialTagsAsCdata; } public boolean isParseSpecialTagsAsCdata() { return this.parseSpecialTagsAsCdata; } /** * Parses provided content. */ protected void parse(TagVisitor visitor) { this.visitor = visitor; long time = 0; if (log.isDebugEnabled()) { log.debug("parsing started"); time = System.currentTimeMillis(); } try { parse(); } catch (IOException ioex) { throw new LagartoException(ioex); } if (log.isDebugEnabled()) { if (time != 0) { time = System.currentTimeMillis() - time; } log.debug("parsing done in " + time + "ms."); } } /** * Main parsing loop that process lexer tokens from input. */ protected void parse() throws IOException{ // set lexer properties lexer.setParseSpecialTagsAsCdata(this.parseSpecialTagsAsCdata); // start visitor.start(); while (true) { Token token = nextToken(); switch (token) { case EOF: flushText(); visitor.end(); return; case COMMENT: parseCommentOrConditionalComment(); break; case CDATA: parseCDATA(); break; case DOCTYPE: parseDoctype(); break; case TEXT: int start = lexer.position(); parseText(start, start + lexer.length()); break; case LT: parseTag(token, TagType.START); break; case XML_LT: parseTag(token, TagType.START); break; case CONDITIONAL_COMMENT_START: parseRevealedCCStart(); break; case CONDITIONAL_COMMENT_END: parseCCEnd(); break; default: error("Unexpected root token: " + token); break; } } } /** * Flushes buffered text and stops buffering. */ protected void flushText() { if (buffering) { visitor.text(input.subSequence(buffTextStart, buffTextEnd)); buffering = false; } } /** * Buffers the parsed text. Buffered text will be consumed * on the very next {@link #flushText()}. */ protected void parseText(int start, int end) { if (!buffering) { buffering = true; buffTextStart = start; buffTextEnd = end; } else { if (buffTextEnd != start) { throw new LagartoException(); } buffTextEnd = end; } } /** * Parses HTML comments. Detect IE hidden conditional comments, too. */ protected void parseCommentOrConditionalComment() throws IOException { flushText(); int start = lexer.position() + 4; // skip "<!--" int end = start + lexer.length() - 7; // skip "-->" if ( (enableConditionalComments) && (LagartoParserUtil.regionStartWith(input, start, end, "[if")) ){ // conditional comment start int expressionEnd = LagartoParserUtil.regionIndexOf(input, start + 3, end, ']'); int ccend = expressionEnd + 2; CharSequence additionalComment = null; // cc start tag ends either with "]>" or at very next "-->" int commentEnd = LagartoParserUtil.regionIndexOf(input, ccend, end, "<![endif]"); if (commentEnd == -1) { additionalComment = input.subSequence(ccend, end + 3); } visitor.condComment(input.subSequence(start + 1, expressionEnd), true, true, additionalComment); // calculate push back to the end of the starting tag if (additionalComment == null) { int pushBack = lexer.position() + lexer.length(); pushBack -= ccend; lexer.yypushback(pushBack); } return; } visitor.comment(input.subSequence(start, end)); } /** * Parses CDATA. */ protected void parseCDATA() throws IOException { flushText(); int start = lexer.position() + 9; int end = start + lexer.length() - 12; visitor.cdata(input.subSequence(start, end)); } /** * Parses HTML DOCTYPE directive. */ protected void parseDoctype() throws IOException { flushText(); skipWhiteSpace(); String name = null; boolean isPublic = false; String publicId = null; String uri = null; int i = 0; while (true) { skipWhiteSpace(); Token token = nextToken(); if (token == Token.GT) { break; } switch (i) { case 0: name = text().toString(); break; case 1: if (text().toString().equals("PUBLIC")) { isPublic = true; } break; case 2: if (isPublic) { publicId = lexer.yytext(1, 1); } else { uri = lexer.yytext(1, 1); break; } break; case 3: uri = lexer.yytext(1, 1); break; } i++; } visitor.doctype(name, publicId, uri); } /** * Parses revealed conditional comment start. * Downlevel-hidden conditional comment is detected in * {@link #parseCommentOrConditionalComment()}. */ protected void parseRevealedCCStart() throws IOException { flushText(); if (enableConditionalComments == false) { error("Conditional comments disabled"); return; } int start = lexer.position(); int end = start + lexer.length(); int textStart = start; int textEnd = end; int i = start + 2; while (i < end) { if (input.charAt(i) == '[') { i++; textStart = i; continue; } if (input.charAt(i) == ']') { textEnd = i; break; } i++; } visitor.condComment(input.subSequence(textStart, textEnd), true, false, null); } /** * Parses conditional comment end. */ protected void parseCCEnd() throws IOException { flushText(); int start = lexer.position(); int end = start + lexer.length(); int textStart = start; int textEnd = end; int i = start + 2; while (i < end) { if (input.charAt(i) == '[') { i++; textStart = i; continue; } if (input.charAt(i) == ']') { textEnd = i; break; } i++; } boolean isDownlevelHidden = (end - textEnd) == 4; boolean hasExtra = (textStart - start) > 3; if (enableConditionalComments == false) { if (isDownlevelHidden) { visitor.comment(input.subSequence(start, end)); } else { error("Conditional comments disabled"); } return; } CharSequence additionalComment = null; if (hasExtra) { additionalComment = input.subSequence(start, textStart - 3); } visitor.condComment(input.subSequence(textStart, textEnd), false, isDownlevelHidden, additionalComment); } /** * Parse tag starting from "&lt;". */ protected void parseTag(Token tagToken, TagType type) throws IOException { int start = lexer.position(); skipWhiteSpace(); Token token; token = nextToken(); // if token is not a special tag ensure // not to scan for special tag name from now on if (lexer.nextTagState == -1) { lexer.nextTagState = -2; } if (token == Token.SLASH) { // it is closing tag type = TagType.END; token = nextToken(); } switch (token) { case WORD: // tag name String tagName = text().toString(); if (acceptTag(tagName)) { parseTagAndAttributes(tagToken, tagName, type, start); } else { // step back and parse tag as text lexer.stateReset(); stepBack(lexer.nextToken()); parseText(start, lexer.position()); } break; case GT: parseText(start, lexer.position() + 1); break; case EOF: // eof, consume it as text parseText(start, lexer.position()); break; default: error("Invalid token in tag <" + text() + '>'); // step back and parse tag as text lexer.stateReset(); stepBack(lexer.nextToken()); parseText(start, lexer.position()); break; } } /** * Returns <code>true</code> if some tag has to be parsed. * User may override this method to gain more control over what should be parsed. * May be used in situations where only few specific tags has to be parsed * (e.g. just title and body). */ @SuppressWarnings({"UnusedParameters"}) protected boolean acceptTag(String tagName) { return true; } /** * Parses full tag. */ protected void parseTagAndAttributes(Token tagToken, String tagName, TagType type, int start) throws IOException { tag.startTag(tagName); Token token; loop: while (true) { skipWhiteSpace(); token = nextToken(); stepBack(token); switch (token) { case SLASH: type = TagType.SELF_CLOSING; // an empty tag, no body nextToken(); break loop; case GT: break loop; case XML_GT: break loop; case WORD: parseAttribute(); break; case EOF: parseText(start, lexer.position()); return; default: // unexpected token, try to skip it! String tokenText = text().toString(); if (tokenText == null) { tokenText = lexer.yytext(); } error("Tag <" + tagName + "> invalid token: " + tokenText); nextToken(); // there was a stepBack, so move forward if (tokenText.length() > 1) { lexer.yypushback(tokenText.length() - 1); } break; } } token = nextToken(); // since the same method is used for XML directive and for TAG, check if (tagToken == Token.LT && token == Token.XML_GT) { token = Token.GT; error("Unmatched tag <" + tagName + "?>"); } else if (tagToken == Token.XML_LT && token == Token.GT) { token = Token.XML_GT; error("Unmatched tag <?" + tagName + '>'); } switch (token) { default: error("Expected end of tag for <" + tagName + '>'); // continue as tag // onTag(type, tagName, start, lexer.position() - start + 1); // break; case GT: // end of tag, process it flushText(); int len = lexer.position() - start + 1; if (type.isStartingTag()) { // parse special tags final int nextTagState = lexer.getNextTagState(); if (nextTagState > 0) { tag.defineTag(type, start, len); tag.increaseDeepLevel(); parseSpecialTag(nextTagState); tag.decreaseDeepLevel(); break; } } // default tag tag.defineTag(type, start, len); if (type.isStartingTag()) { tag.increaseDeepLevel(); } visitor.tag(tag); if (type.isEndingTag()) { tag.decreaseDeepLevel(); } break; case XML_GT: flushText(); int len2 = lexer.position() - start + 2; tag.defineTag(type, start, len2); tag.setTagMarks("<?", "?>"); tag.increaseDeepLevel(); visitor.xml(tag); tag.decreaseDeepLevel(); break; case EOF: parseText(start, lexer.position()); break; } } /** * Parses single attribute. */ protected void parseAttribute() throws IOException { nextToken(); String attributeName = text().toString(); skipWhiteSpace(); Token token = nextToken(); if (token == Token.EQUALS) { skipWhiteSpace(); token = nextToken(); if (token == Token.QUOTE) { CharSequence charSequence = text(); char quote = charSequence.charAt(0); charSequence = charSequence.subSequence(1, charSequence.length() - 1); String attributeValue = charSequence.toString(); if (quote == '\'') { attributeValue = StringUtil.replace(attributeValue, StringPool.QUOTE, HTML_QUOTE); } tag.addAttribute(attributeName, attributeValue); } else if (token == Token.WORD) { // attribute value is not quoted, take everything until the space or tag end as a value String attributeValue = text().toString(); while (true) { Token next = nextToken(); if (next != Token.WHITESPACE && next != Token.GT) { attributeValue += text(); // rare, keep joining attribute value with tokens } else { stepBack(next); break; } } tag.addAttribute(attributeName, attributeValue); } else if (token == Token.SLASH || token == Token.GT) { stepBack(token); } else if (token != Token.EOF) { error("Invalid attribute: " + attributeName); } } else if (token == Token.SLASH || token == Token.GT || token == Token.WORD) { tag.addAttribute(attributeName, null); stepBack(token); } else if (token == Token.QUOTE) { error("Orphan attribute: " + text()); tag.addAttribute(attributeName, null); } else if (token != Token.EOF) { error("Invalid attribute: " + attributeName); } } /** * Parses special tags. */ protected void parseSpecialTag(int state) throws IOException { int start = lexer.position() + 1; nextToken(); int end = start + lexer.length(); switch(state) { case Lexer.XMP: visitor.xmp(tag, input.subSequence(start, end - 6)); break; case Lexer.SCRIPT: visitor.script(tag, input.subSequence(start, end - 9)); break; case Lexer.STYLE: visitor.style(tag, input.subSequence(start, end - 8)); break; } } /** * Step back lexer position. */ private void stepBack(Token next) { if (lastToken != Token.UNKNOWN) { throw new LagartoException("Only one step back allowed."); } lastToken = next; if (next == Token.WORD || next == Token.QUOTE || next == Token.SLASH || next == Token.EQUALS) { lastText = lexer.xxtext(); } else { lastText = null; } } /** * Returns the next token from lexer or previously fetched token. */ protected Token nextToken() throws IOException { Token next; if (lastToken == Token.UNKNOWN) { next = lexer.nextToken(); } else { next = lastToken; lastToken = Token.UNKNOWN; } return next; } /** * Skips all whitespace tokens. */ protected void skipWhiteSpace() throws IOException { while (true) { Token next; next = nextToken(); if (next != Token.WHITESPACE) { stepBack(next); break; } } } /** * Returns current text. */ protected CharSequence text() { if (lastToken == Token.UNKNOWN) { return lexer.xxtext(); } else { return lastText; } } /** * Prepares error message and reports it to the visitor. */ protected void error(String message) { int line = lexer.line(); int column = lexer.column(); if (message == null) { message = StringPool.EMPTY; } if (line != -1) { // position is detected by jflex message += " [" + line + ':' + column + ']'; } else { int position = lexer.position(); if (calculatePosition == false) { message += " [@" + position + ']'; } else { LagartoLexer.Position currentPosition = lexer.currentPosition(); message += ' ' + currentPosition.toString(); } } visitor.error(message); } }
package springBootExample.controller; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.google.gson.Gson; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import springBootExample.model.entity.User; import springBootExample.model.json.UserDto; import springBootExample.model.repository.UserRepository; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class UserControllerTest { private MockMvc mvc; @Mock private UserRepository mockRepo; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); mvc = MockMvcBuilders.standaloneSetup(new UserController(mockRepo)).build(); } @Test public void getUser() throws Exception { Long userId = 1l; User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); when(mockRepo.userExists(userId.toString())).thenReturn(true); when(mockRepo.findOne(userId)).thenReturn(user); mvc.perform(MockMvcRequestBuilders.get("/user/" + userId)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"id\":" + userId.toString() + ",\"email\":\"pacitu@abv.bg\",\"firstName\":\"Pavel\",\"lastName\":\"Kostadinov\",\"dateOfBirth\":\"1985-04-04\"}"))); } @Test public void getMissingUser() throws Exception { Long userId = 1l; when(mockRepo.userExists(userId.toString())).thenReturn(false); mvc.perform(MockMvcRequestBuilders.get("/user/" + userId)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"general : User does not exist.\"]}"))); } @Test public void getUsers() throws Exception { List<User> expectedPeople = asList(new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04")); when(mockRepo.findAll()).thenReturn(expectedPeople); mvc.perform(MockMvcRequestBuilders.get("/user")) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[{\"id\":0,\"email\":\"pacitu@abv.bg\",\"firstName\":\"Pavel\",\"lastName\":\"Kostadinov\",\"dateOfBirth\":\"1985-04-04\"}]"))); } @Test public void deleteUser() throws Exception { Long userId = 1l; when(mockRepo.userExists(userId.toString())).thenReturn(true); mvc.perform(MockMvcRequestBuilders.delete("/user/" + userId)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"success\":true}"))); Mockito.verify(mockRepo, times(1)).delete(userId); } @Test public void deleteMissingUser() throws Exception { Long userId = 1l; when(mockRepo.userExists(userId.toString())).thenReturn(false); mvc.perform(MockMvcRequestBuilders.delete("/user/" + userId)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"general : User does not exist.\"]}"))); } @Test public void updateUser() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", "Pavel", "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); when(mockRepo.userExists(userId.toString())).thenReturn(true); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.put("/user/" + userId.toString()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"id\":" + userId.toString() + ",\"email\":\"pacitu@abv.bg\",\"firstName\":\"Pavel\",\"lastName\":\"Kostadinov\",\"dateOfBirth\":\"1985-04-04\"}"))); Mockito.verify(mockRepo, times(1)).save(user); } @Test public void updateUserMalformedEmail() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "Hello world!", "Pavel", "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); when(mockRepo.userExists(userId.toString())).thenReturn(true); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.put("/user/" + userId.toString()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"email : not a well-formed email address\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void updateUserMissingEmail() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, null, "Pavel", "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); when(mockRepo.userExists(userId.toString())).thenReturn(true); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.put("/user/" + userId.toString()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"email : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void updateUserMissingFirstName() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", null, "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); when(mockRepo.userExists(userId.toString())).thenReturn(true); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.put("/user/" + userId.toString()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"firstName : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void updateUserMissingLastName() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", "Pavel", null, "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); when(mockRepo.userExists(userId.toString())).thenReturn(true); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.put("/user/" + userId.toString()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"lastName : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void updateUserMissingDateOfBirth() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", "Pavel", "Kostadinov", null); Gson gson = new Gson(); String json = gson.toJson(userDto); when(mockRepo.userExists(userId.toString())).thenReturn(true); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.put("/user/" + userId.toString()) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"dateOfBirth : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void addUser() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", "Pavel", "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"id\":" + userId.toString() + ",\"email\":\"pacitu@abv.bg\",\"firstName\":\"Pavel\",\"lastName\":\"Kostadinov\",\"dateOfBirth\":\"1985-04-04\"}"))); Mockito.verify(mockRepo, times(1)).save(user); } @Test public void addUserMalformedEmail() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "Hello world!", "Pavel", "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"email : not a well-formed email address\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void addUserMissingEmail() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, null, "Pavel", "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"email : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void addUserMissingFirstName() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", null, "Kostadinov", "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"firstName : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void addUserMissingLastName() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", "Pavel", null, "1985-04-04"); Gson gson = new Gson(); String json = gson.toJson(userDto); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"lastName : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } @Test public void addUserMissingDateOfBirth() throws Exception { Long userId = 1l; UserDto userDto = new UserDto(userId, "pacitu@abv.bg", "Pavel", "Kostadinov", null); Gson gson = new Gson(); String json = gson.toJson(userDto); User user = new User("Pavel", "Kostadinov", "pacitu@abv.bg", "1985-04-04"); user.setId(userId); mvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(equalTo("{\"errors\":[\"dateOfBirth : may not be null\"]}"))); Mockito.verify(mockRepo, times(0)).save(user); } }
package org.modmine.web; import java.util.HashSet; import java.util.List; import java.util.Set; 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.intermine.api.InterMineAPI; import org.intermine.api.bag.BagQueryRunner; import org.intermine.api.profile.Profile; import org.intermine.api.query.WebResultsExecutor; import org.intermine.api.results.WebResults; import org.intermine.api.util.NameUtil; import org.intermine.metadata.Model; import org.intermine.model.bio.Submission; import org.intermine.objectstore.ObjectStore; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.PathQuery; import org.intermine.util.StringUtil; import org.intermine.web.logic.bag.BagHelper; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.export.http.TableExporterFactory; import org.intermine.web.logic.export.http.TableHttpExporter; import org.intermine.web.logic.results.PagedTable; import org.intermine.web.logic.session.SessionMethods; import org.intermine.web.struts.ForwardParameters; import org.intermine.web.struts.InterMineAction; /** * Generate queries for overlaps of submission features and overlaps with gene flanking regions. * @author Richard Smith * */ public class FeaturesAction extends InterMineAction { /** * Action for creating a bag of InterMineObjects or Strings from identifiers in text field. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ // private static final Logger LOG = Logger.getLogger(MetadataCache.class); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); ObjectStore os = im.getObjectStore(); Model model = im.getModel(); String type = (String) request.getParameter("type"); String featureType = (String) request.getParameter("feature"); String action = (String) request.getParameter("action"); String dccId = null; String experimentName = null; PathQuery q = new PathQuery(model); boolean hasPrimer = false; if (type.equals("experiment")) { experimentName = (String) request.getParameter("experiment"); DisplayExperiment exp = MetadataCache.getExperimentByName(os, experimentName); List<String> expSubsIds = exp.getSubmissionsDccId(); Set<String> allUnlocated = new HashSet<String>(); hasPrimer = false; String ef = getFactors(exp); if (ef.contains("primer")){ hasPrimer = true; } String description = "All " + featureType + " features generated by experiment '" + exp.getName() + "' in " + StringUtil.prettyList(exp.getOrganisms()) + " (" + exp.getPi() + ")." + ef; q.setDescription(description); for (String subId : expSubsIds){ if (MetadataCache.getUnlocatedFeatureTypes(os).containsKey(new Integer(subId))){ allUnlocated.addAll(MetadataCache.getUnlocatedFeatureTypes(os).get(new Integer(subId))); } } if (allUnlocated.contains(featureType)){ // temporary until we remove primers from factors if (hasPrimer){ q.addView(featureType + ".primaryIdentifier"); q.addView(featureType + ".score"); q.addConstraint(featureType + ".submissions.experiment.name", Constraints.eq(experimentName)); } else { q.addView(featureType + ".primaryIdentifier"); q.addView(featureType + ".score"); q.addView(featureType + ".submissions:experimentalFactors.type"); q.addView(featureType + ".submissions:experimentalFactors.name"); q.addConstraint(featureType + ".submissions.experiment.name", Constraints.eq(experimentName)); } } else { q.addView(featureType + ".primaryIdentifier"); q.addView(featureType + ".score"); q.addView(featureType + ".chromosome.primaryIdentifier"); q.addView(featureType + ".chromosomeLocation.start"); q.addView(featureType + ".chromosomeLocation.end"); q.addView(featureType + ".chromosomeLocation.strand"); q.addView(featureType + ".submissions.DCCid"); q.addConstraint(featureType + ".submissions.experiment.name", Constraints.eq(experimentName)); q.addOrderBy(featureType + ".chromosome.primaryIdentifier"); q.addOrderBy(featureType + ".chromosomeLocation.start"); if (!hasPrimer) { q.addView(featureType + ".submissions:experimentalFactors.type"); q.addView(featureType + ".submissions:experimentalFactors.name"); } } } else if (type.equals("submission")) { dccId = (String) request.getParameter("submission"); Submission sub = MetadataCache.getSubmissionByDccId(os, new Integer(dccId)); List<String> unlocFeatures = MetadataCache.getUnlocatedFeatureTypes(os).get(new Integer(dccId)); hasPrimer = false; // to build the query description String experimentType = ""; if (sub.getExperimentType() != null) { experimentType = StringUtil.indefiniteArticle(sub.getExperimentType()) + " " + sub.getExperimentType() + " experiment in"; } String efSub = ""; if (SubmissionHelper.getExperimentalFactorString(sub).length() > 1){ efSub = " using " + SubmissionHelper.getExperimentalFactorString(sub); if (efSub.contains("primer")){ hasPrimer = true; efSub = ""; } } String description = "All " + featureType + " features generated by submission " + dccId + ", " + experimentType + " " + sub.getOrganism().getShortName() + efSub + " (" + sub.getProject().getSurnamePI() + ")."; q.setDescription(description); if (unlocFeatures == null || unlocFeatures.contains(featureType)){ if (hasPrimer){ q.addView(featureType + ".primaryIdentifier"); q.addView(featureType + ".score"); q.addConstraint(featureType + ".submissions.DCCid", Constraints.eq(new Integer(dccId))); } else { q.addView(featureType + ".primaryIdentifier"); q.addView(featureType + ".score"); q.addView(featureType + ".submissions:experimentalFactors.type"); q.addView(featureType + ".submissions:experimentalFactors.name"); q.addConstraint(featureType + ".submissions.DCCid", Constraints.eq(new Integer(dccId))); } } else { q.addView(featureType + ".primaryIdentifier"); q.addView(featureType + ".score"); q.addView(featureType + ".chromosome.primaryIdentifier"); q.addView(featureType + ".chromosomeLocation.start"); q.addView(featureType + ".chromosomeLocation.end"); q.addView(featureType + ".chromosomeLocation.strand"); q.addView(featureType + ".submissions.DCCid"); q.addConstraint(featureType + ".submissions.DCCid", Constraints.eq(new Integer(dccId))); q.addOrderBy(featureType + ".chromosome.primaryIdentifier"); q.addOrderBy(featureType + ".chromosomeLocation.start"); if (!hasPrimer) { q.addView(featureType + ".submissions:experimentalFactors.type"); q.addView(featureType + ".submissions:experimentalFactors.name"); } } } if (action.equals("results")) { String qid = SessionMethods.startQueryWithTimeout(request, false, q); Thread.sleep(200); return new ForwardParameters(mapping.findForward("waiting")) .addParameter("qid", qid) .forward(); } else if (action.equals("export")) { String format = request.getParameter("format"); Profile profile = SessionMethods.getProfile(session); WebResultsExecutor executor = im.getWebResultsExecutor(profile); PagedTable pt = new PagedTable(executor.execute(q)); if (pt.getWebTable() instanceof WebResults) { ((WebResults) pt.getWebTable()).goFaster(); } WebConfig webConfig = SessionMethods.getWebConfig(request); TableExporterFactory factory = new TableExporterFactory(webConfig); TableHttpExporter exporter = factory.getExporter(format); if (exporter == null) { throw new RuntimeException("unknown export format: " + format); } exporter.export(pt, request, response, null); // If null is returned then no forwarding is performed and // to the output is not flushed any jsp output, so user // will get only required export data return null; } else if (action.equals("list")) { // need to select just id of featureType to create list q.setView(featureType + ".id"); Profile profile = SessionMethods.getProfile(session); BagQueryRunner bagQueryRunner = im.getBagQueryRunner(); String bagName = (dccId != null ? "submission_" + dccId : experimentName) + "_" + featureType + "_features"; bagName = NameUtil.generateNewName(profile.getSavedBags().keySet(), bagName); BagHelper.createBagFromPathQuery(q, bagName, q.getDescription(), featureType, profile, os, bagQueryRunner); ForwardParameters forwardParameters = new ForwardParameters(mapping.findForward("bagDetails")); return forwardParameters.addParameter("bagName", bagName).forward(); } return null; } private String getFactors(DisplayExperiment exp) { String ef = ""; if (exp.getFactorTypes().size() == 1){ ef = "Experimental factor is the " + StringUtil.prettyList(exp.getFactorTypes()) + " used." ; } if (exp.getFactorTypes().size() > 1){ ef = "Experimental factors are the " + StringUtil.prettyList(exp.getFactorTypes()) + " used." ; } return ef; } }
package uk.co.jemos.podam.test.unit; import java.math.BigDecimal; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.activation.DataHandler; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import uk.co.jemos.podam.api.PodamFactory; import uk.co.jemos.podam.api.PodamFactoryImpl; import uk.co.jemos.podam.api.RandomDataProviderStrategy; import uk.co.jemos.podam.exceptions.PodamMockeryException; import uk.co.jemos.podam.test.dto.AbstractTestPojo; import uk.co.jemos.podam.test.dto.CollectionsPojo; import uk.co.jemos.podam.test.dto.ConstructorWithSelfReferencesButNoDefaultConstructorPojo; import uk.co.jemos.podam.test.dto.ConstructorWithSelfReferencesPojo; import uk.co.jemos.podam.test.dto.EnumsPojo; import uk.co.jemos.podam.test.dto.EnumsPojo.RatePodamInternal; import uk.co.jemos.podam.test.dto.ExcludeAnnotationPojo; import uk.co.jemos.podam.test.dto.ImmutableNoHierarchicalAnnotatedPojo; import uk.co.jemos.podam.test.dto.ImmutableNonAnnotatedPojo; import uk.co.jemos.podam.test.dto.ImmutableWithGenericCollectionsPojo; import uk.co.jemos.podam.test.dto.ImmutableWithNonGenericCollectionsPojo; import uk.co.jemos.podam.test.dto.InterfacePojo; import uk.co.jemos.podam.test.dto.NoDefaultConstructorPojo; import uk.co.jemos.podam.test.dto.NoSetterWithCollectionInConstructorPojo; import uk.co.jemos.podam.test.dto.OneDimensionalChildPojo; import uk.co.jemos.podam.test.dto.OneDimensionalTestPojo; import uk.co.jemos.podam.test.dto.PrivateNoArgConstructorPojo; import uk.co.jemos.podam.test.dto.RecursivePojo; import uk.co.jemos.podam.test.dto.SimplePojoToTestSetters; import uk.co.jemos.podam.test.dto.SingletonWithParametersInStaticFactoryPojo; import uk.co.jemos.podam.test.dto.annotations.BooleanValuePojo; import uk.co.jemos.podam.test.dto.annotations.ByteValuePojo; import uk.co.jemos.podam.test.dto.annotations.ByteValueWithErrorPojo; import uk.co.jemos.podam.test.dto.annotations.CharValuePojo; import uk.co.jemos.podam.test.dto.annotations.CollectionAnnotationPojo; import uk.co.jemos.podam.test.dto.annotations.DoubleValuePojo; import uk.co.jemos.podam.test.dto.annotations.DoubleValueWithErrorPojo; import uk.co.jemos.podam.test.dto.annotations.FloatValuePojo; import uk.co.jemos.podam.test.dto.annotations.FloatValueWithErrorPojo; import uk.co.jemos.podam.test.dto.annotations.IntegerValuePojo; import uk.co.jemos.podam.test.dto.annotations.IntegerValueWithErrorPojo; import uk.co.jemos.podam.test.dto.annotations.LongValuePojo; import uk.co.jemos.podam.test.dto.annotations.LongValueWithErrorPojo; import uk.co.jemos.podam.test.dto.annotations.PodamStrategyPojo; import uk.co.jemos.podam.test.dto.annotations.ShortValuePojo; import uk.co.jemos.podam.test.dto.annotations.ShortValueWithErrorPojo; import uk.co.jemos.podam.test.dto.annotations.StringValuePojo; import uk.co.jemos.podam.test.dto.annotations.StringWithWrongStrategyTypePojo; import uk.co.jemos.podam.test.dto.pdm33.NoDefaultPublicConstructorPojo; import uk.co.jemos.podam.test.dto.pdm33.PrivateOnlyConstructorPojo; import uk.co.jemos.podam.test.dto.pdm33.ProtectedNonDefaultConstructorPojo; import uk.co.jemos.podam.test.dto.pdm6.Child; import uk.co.jemos.podam.test.dto.pdm6.Parent; import uk.co.jemos.podam.test.dto.pdm6.RecursiveList; import uk.co.jemos.podam.test.dto.pdm6.RecursiveMap; import uk.co.jemos.podam.test.enums.ExternalRatePodamEnum; import uk.co.jemos.podam.test.utils.PodamTestConstants; import uk.co.jemos.podam.test.utils.PodamTestUtils; /** * Unit test for simple App. */ public class PodamMockerUnitTest { /** The podam factory */ private PodamFactory factory; /** The default data strategy */ private final RandomDataProviderStrategy strategy = RandomDataProviderStrategy .getInstance(); @Before public void init() { factory = new PodamFactoryImpl(strategy); } @Test public void testMockerForClassWithoutDefaultConstructor() { // With a no-arg constructor, an instantiation exception will be thrown NoDefaultConstructorPojo pojo = factory .manufacturePojo(NoDefaultConstructorPojo.class); Assert.assertNotNull( "The pojo with no default constructors must not be null!", pojo); } @Test public void testMockerForAbstractClass() { // Trying to create an abstract class should thrown an instantiation // exception AbstractTestPojo pojo = factory.manufacturePojo(AbstractTestPojo.class); Assert.assertNull("The abstract pojo should be null!", pojo); } @Test public void testMockerForInterface() { // Trying to create an interface class should thrown an instantiation // exception InterfacePojo pojo = factory.manufacturePojo(InterfacePojo.class); Assert.assertNull("The interface pojo should be null!", pojo); } @Test public void testMockerForPrimitiveType() { // Trying to create an interface class should thrown an instantiation // exception int intValue = factory.manufacturePojo(int.class); Assert.assertTrue("The int value should not be zero!", intValue != 0); } @Test public void testMockerForPojoWithPrivateNoArgConstructor() { PrivateNoArgConstructorPojo pojo = factory .manufacturePojo(PrivateNoArgConstructorPojo.class); Assert.assertNotNull( "The pojo with private default constructor cannot be null!", pojo); } @Test public void testOneDimensionalTestPojo() { OneDimensionalTestPojo pojo = factory .manufacturePojo(OneDimensionalTestPojo.class); Assert.assertNotNull("The object cannot be null!", pojo); Boolean booleanObjectField = pojo.getBooleanObjectField(); Assert.assertTrue( "The boolean object field should have a value of TRUE", booleanObjectField); boolean booleanField = pojo.isBooleanField(); Assert.assertTrue("The boolean field should have a value of TRUE", booleanField); byte byteField = pojo.getByteField(); Assert.assertTrue("The byte field should not be zero", byteField != 0); Byte byteObjectField = pojo.getByteObjectField(); Assert.assertTrue("The Byte object field should not be zero", byteObjectField != 0); short shortField = pojo.getShortField(); Assert.assertTrue("The short field should not be zero", shortField != 0); Short shortObjectField = pojo.getShortObjectField(); Assert.assertTrue("The Short Object field should not be zero", shortObjectField != 0); char charField = pojo.getCharField(); Assert.assertTrue("The char field should not be zero", charField != 0); Character characterObjectField = pojo.getCharObjectField(); Assert.assertTrue("The Character object field should not be zero", characterObjectField != 0); int intField = pojo.getIntField(); Assert.assertTrue("The int field cannot be zero", intField != 0); Integer integerField = pojo.getIntObjectField(); Assert.assertTrue("The Integer object field cannot be zero", integerField != 0); long longField = pojo.getLongField(); Assert.assertTrue("The long field cannot be zero", longField != 0); Long longObjectField = pojo.getLongObjectField(); Assert.assertTrue("The Long object field cannot be zero", longObjectField != 0); float floatField = pojo.getFloatField(); Assert.assertTrue("The float field cannot be zero", floatField != 0.0); Float floatObjectField = pojo.getFloatObjectField(); Assert.assertTrue("The Float object field cannot be zero", floatObjectField != 0.0); double doubleField = pojo.getDoubleField(); Assert.assertTrue("The double field cannot be zero", doubleField != 0.0d); Double doubleObjectField = pojo.getDoubleObjectField(); Assert.assertTrue("The Double object field cannot be zero", doubleObjectField != 0.0d); String stringField = pojo.getStringField(); Assert.assertNotNull("The String field cannot be null", stringField); Assert.assertFalse("The String field cannot be empty", stringField.equals("")); Object objectField = pojo.getObjectField(); Assert.assertNotNull("The Object field cannot be null", objectField); Calendar calendarField = pojo.getCalendarField(); checkCalendarIsValid(calendarField); Date dateField = pojo.getDateField(); Assert.assertNotNull("The date field is not valid", dateField); Random[] randomArray = pojo.getRandomArray(); Assert.assertNotNull("The array of Random objects cannot be null!", randomArray); Assert.assertEquals("The array of Random length should be one!", strategy.getNumberOfCollectionElements(Random.class), randomArray.length); Random random = randomArray[0]; Assert.assertNotNull( "The Random array element at [0] should not be null", random); int[] intArray = pojo.getIntArray(); Assert.assertNotNull("The array of ints cannot be null!", intArray); Assert.assertEquals( "The array of ints length should be the same as defined in the strategy!", strategy.getNumberOfCollectionElements(Integer.class), intArray.length); Assert.assertTrue( "The first element in the array of ints must be different from zero!", intArray[0] != 0); boolean[] booleanArray = pojo.getBooleanArray(); Assert.assertNotNull("The array of booleans cannot be null!", booleanArray); Assert.assertEquals( "The array of boolean length should be the same as the one set in the strategy!", strategy.getNumberOfCollectionElements(Boolean.class), booleanArray.length); BigDecimal bigDecimalField = pojo.getBigDecimalField(); Assert.assertNotNull("The BigDecimal field cannot be null!", bigDecimalField); } @Test public void testRecursiveHierarchyPojo() { RecursivePojo pojo = factory.manufacturePojo(RecursivePojo.class); Assert.assertNotNull("The recursive pojo cannot be null!", pojo); Assert.assertTrue("The integer value in the pojo should not be zero!", pojo.getIntField() != 0); RecursivePojo parentPojo = pojo.getParent(); Assert.assertNotNull("The parent pojo cannot be null!", parentPojo); Assert.assertTrue( "The integer value in the parent pojo should not be zero!", parentPojo.getIntField() != 0); Assert.assertNotNull( "The parent attribute of the parent pojo cannot be null!", parentPojo.getParent()); } @Test public void testCircularDependencyPojos() { Parent parent = factory.manufacturePojo(Parent.class); Assert.assertNotNull("The parent pojo cannot be null!", parent); Child child = parent.getChild(); Assert.assertNotNull("The child pojo cannot be null!", child); } @Test public void testCircularDependencyCollection() { RecursiveList pojo = factory.manufacturePojo(RecursiveList.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Assert.assertNotNull("The pojo's list cannot be null!", pojo.getList()); Assert.assertTrue("The pojo's list cannot be empty!", !pojo.getList().isEmpty()); for (RecursiveList listValue : pojo.getList()) { Assert.assertNotNull( "The pojo's list element cannot be null!", listValue); } } @Test public void testCircularDependencyMap() { RecursiveMap pojo = factory.manufacturePojo(RecursiveMap.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Assert.assertNotNull("The pojo's map cannot be null!", pojo.getMap()); Assert.assertTrue("The pojo's map cannot be empty!", !pojo.getMap().isEmpty()); for (RecursiveMap mapValue : pojo.getMap().values()) { Assert.assertNotNull( "The pojo's map element cannot be null!", mapValue); } } @Test public void testJREPojoWithDependencyLoopInConstructor() { URL pojo = factory.manufacturePojo(URL.class); Assert.assertNull("Default strategy cannot create java.net.URL object", pojo); DataHandler pojo2 = factory.manufacturePojo(DataHandler.class); Assert.assertNotNull("The pojo cannot be null!", pojo2); } @Test public void testImmutableNoHierarchicalAnnotatedPojo() { ImmutableNoHierarchicalAnnotatedPojo pojo = factory .manufacturePojo(ImmutableNoHierarchicalAnnotatedPojo.class); Assert.assertNotNull("The Immutable Simple Pojo cannot be null!", pojo); int intField = pojo.getIntField(); Assert.assertTrue("The int field cannot be zero", intField != 0); Calendar dateCreated = pojo.getDateCreated(); Assert.assertNotNull( "The Date Created Calendar object cannot be null!", dateCreated); Assert.assertNotNull( "The Date object within the dateCreated Calendar object cannot be null!", dateCreated.getTime()); long[] longArray = pojo.getLongArray(); Assert.assertNotNull("The array of longs cannot be null!", longArray); Assert.assertTrue("The array of longs cannot be empty!", longArray.length > 0); long longElement = longArray[0]; Assert.assertTrue( "The long element within the long array cannot be zero!", longElement != 0); } @Test public void testImmutableNonAnnotatedPojo() { ImmutableNonAnnotatedPojo pojo = factory .manufacturePojo(ImmutableNonAnnotatedPojo.class); Assert.assertNotNull( "The immutable non annotated POJO should not be null!", pojo); Assert.assertNotNull("The date created cannot be null!", pojo.getDateCreated()); Assert.assertTrue("The int field cannot be zero!", pojo.getIntField() != 0); long[] longArray = pojo.getLongArray(); Assert.assertNotNull("The array of longs cannot be null!", longArray); Assert.assertEquals("The array of longs must have 1 element!", strategy.getNumberOfCollectionElements(Long.class), longArray.length); } @Test public void testPojoWithSelfReferencesInConstructor() { ConstructorWithSelfReferencesPojo pojo = factory .manufacturePojo(ConstructorWithSelfReferencesPojo.class); Assert.assertNotNull("The POJO cannot be null!", pojo); Assert.assertNotNull("The first self-reference cannot be null!", pojo.getParent()); Assert.assertNotNull("The second self-reference cannot be null!", pojo.getAnotherParent()); } @Test(expected = PodamMockeryException.class) public void testPojoWithSelfReferenceInConstructorButNoDefaultConstructor() { factory.manufacturePojo(ConstructorWithSelfReferencesButNoDefaultConstructorPojo.class); } @Test public void testPodamExcludeAnnotation() { ExcludeAnnotationPojo pojo = factory .manufacturePojo(ExcludeAnnotationPojo.class); Assert.assertNotNull("The pojo should not be null!", pojo); int intField = pojo.getIntField(); Assert.assertTrue("The int field should not be zero!", intField != 0); Assert.assertNull( "The other object in the pojo should be null because annotated with PodamExclude!", pojo.getSomePojo()); } @Test public void testIntegerValueAnnotation() { IntegerValuePojo pojo = factory.manufacturePojo(IntegerValuePojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); int intFieldWithMinValueOnly = pojo.getIntFieldWithMinValueOnly(); Assert.assertTrue("The int field with only minValue should be >= 0", intFieldWithMinValueOnly >= 0); int intFieldWithMaxValueOnly = pojo.getIntFieldWithMaxValueOnly(); Assert.assertTrue( "The int field with maximum value only should have a maximum value of 100", intFieldWithMaxValueOnly <= 100); int intObjectFieldWithMinAndMaxValue = pojo .getIntFieldWithMinAndMaxValue(); Assert.assertTrue( "The int field with both min and max value should have a value comprised between", intObjectFieldWithMinAndMaxValue >= 0 && intObjectFieldWithMinAndMaxValue <= 1000); Integer integerObjectFieldWithMinValueOnly = pojo .getIntegerObjectFieldWithMinValueOnly(); Assert.assertNotNull( "The integer field with minimum value only should not be null!", integerObjectFieldWithMinValueOnly); Assert.assertTrue( "The integer field with minimum value only should have a minimum value greater or equal to zero!", integerObjectFieldWithMinValueOnly.intValue() >= 0); Integer integerObjectFieldWithMaxValueOnly = pojo .getIntegerObjectFieldWithMaxValueOnly(); Assert.assertNotNull( "The integer field with maximum value only should not be null!", integerObjectFieldWithMaxValueOnly); Assert.assertTrue( "The integer field with maximum value only should have a maximum value of 100", integerObjectFieldWithMaxValueOnly.intValue() <= 100); Integer integerObjectFieldWithMinAndMaxValue = pojo .getIntegerObjectFieldWithMinAndMaxValue(); Assert.assertNotNull( "The integer field with minimum and maximum value should not be null!", integerObjectFieldWithMinAndMaxValue); Assert.assertTrue( "The integer field with minimum and maximum value should have value comprised between 0 and 1000", integerObjectFieldWithMinAndMaxValue.intValue() >= 0 && integerObjectFieldWithMinAndMaxValue.intValue() <= 1000); int intFieldWithPreciseValue = pojo.getIntFieldWithPreciseValue(); Assert.assertTrue( "The integer field with precise value must have a value of: " + PodamTestConstants.INTEGER_PRECISE_VALUE, intFieldWithPreciseValue == Integer .valueOf(PodamTestConstants.INTEGER_PRECISE_VALUE)); Integer integerObjectFieldWithPreciseValue = pojo .getIntegerObjectFieldWithPreciseValue(); Assert.assertNotNull( "The integer object field with precise value cannot be null!", integerObjectFieldWithPreciseValue); Assert.assertTrue( "The integer object field with precise value should have a value of " + PodamTestConstants.INTEGER_PRECISE_VALUE, integerObjectFieldWithPreciseValue.intValue() == Integer .valueOf(PodamTestConstants.INTEGER_PRECISE_VALUE)); } @Test(expected = PodamMockeryException.class) public void testIntegerValueAnnotationWithNumberFormatError() { factory.manufacturePojo(IntegerValueWithErrorPojo.class); } @Test public void testLongValueAnnotation() { LongValuePojo pojo = factory.manufacturePojo(LongValuePojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); long longFieldWithMinValueOnly = pojo.getLongFieldWithMinValueOnly(); Assert.assertTrue( "The long field with min value only should have a value >= 0", longFieldWithMinValueOnly >= 0); long longFieldWithMaxValueOnly = pojo.getLongFieldWithMaxValueOnly(); Assert.assertTrue( "The long field with maximumm value only should have a maximum value of 100", longFieldWithMaxValueOnly <= 100); long longFieldWithMinAndMaxValue = pojo .getLongFieldWithMinAndMaxValue(); Assert.assertTrue( "The long field with both min and max value should have a value comprised between 0 and 1000!", longFieldWithMinAndMaxValue >= 0 && longFieldWithMinAndMaxValue <= 1000); Long longObjectFieldWithMinValueOnly = pojo .getLongObjectFieldWithMinValueOnly(); Assert.assertNotNull( "The Long Object field with min value only cannot be null!", longObjectFieldWithMinValueOnly); Assert.assertTrue( "The Long Object field with min value only should have a value >= 0", longObjectFieldWithMinValueOnly >= 0); Long longObjectFieldWithMaxValueOnly = pojo .getLongObjectFieldWithMaxValueOnly(); Assert.assertNotNull( "The Long Object field with max value only cannot be null!", longObjectFieldWithMaxValueOnly); Assert.assertTrue( "The Long Object field with max value only should have a value <= 100", longObjectFieldWithMaxValueOnly <= 100); Long longObjectFieldWithMinAndMaxValue = pojo .getLongObjectFieldWithMinAndMaxValue(); Assert.assertNotNull( "The Long Object field with min and max value cannot be null!", longObjectFieldWithMinAndMaxValue); Assert.assertTrue( "The Long object field with min and max value should have a value comprised between 0 and 1000", longObjectFieldWithMinAndMaxValue >= 0L && longObjectFieldWithMinAndMaxValue <= 1000L); long longFieldWithPreciseValue = pojo.getLongFieldWithPreciseValue(); Assert.assertTrue( "The long field with precise value must have a value of " + PodamTestConstants.LONG_PRECISE_VALUE, longFieldWithPreciseValue == Long .valueOf(PodamTestConstants.LONG_PRECISE_VALUE)); Long longObjectFieldWithPreciseValue = pojo .getLongObjectFieldWithPreciseValue(); Assert.assertNotNull( "The long object with precise value should not be null!", longObjectFieldWithPreciseValue); Assert.assertTrue( "The long object field with precise value must have a value of " + PodamTestConstants.LONG_PRECISE_VALUE, longObjectFieldWithPreciseValue.longValue() == Long.valueOf( PodamTestConstants.LONG_PRECISE_VALUE).longValue()); } @Test(expected = PodamMockeryException.class) public void testLongValueAnnotationWithNumberFormatException() { factory.manufacturePojo(LongValueWithErrorPojo.class); } @Test public void testInheritance() { OneDimensionalChildPojo pojo = factory .manufacturePojo(OneDimensionalChildPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); int parentIntField = pojo.getParentIntField(); Assert.assertTrue("The super int field must be <= 10", parentIntField <= 10); Calendar parentCalendarField = pojo.getParentCalendarField(); checkCalendarIsValid(parentCalendarField); int intField = pojo.getIntField(); Assert.assertTrue("The int field must be different from zero!", intField != 0); String strField = pojo.getStrField(); Assert.assertNotNull("The string field cannot be null!", strField); Assert.assertTrue("The String field cannot be empty", strField.length() != 0); } @Test public void testCollectionsPojo() { CollectionsPojo pojo = factory.manufacturePojo(CollectionsPojo.class); Assert.assertNotNull("The POJO cannot be null!", pojo); List<String> strList = pojo.getStrList(); validateReturnedList(strList); ArrayList<String> arrayListStr = pojo.getArrayListStr(); validateReturnedList(arrayListStr); List<String> copyOnWriteList = pojo.getCopyOnWriteList(); validateReturnedList(copyOnWriteList); HashSet<String> hashSetStr = pojo.getHashSetStr(); validateReturnedSet(hashSetStr); List<String> listStrCollection = new ArrayList<String>( pojo.getStrCollection()); validateReturnedList(listStrCollection); Set<String> setStrCollection = new HashSet<String>( pojo.getStrCollection()); validateReturnedSet(setStrCollection); Set<String> strSet = pojo.getStrSet(); validateReturnedSet(strSet); Map<String, OneDimensionalTestPojo> map = pojo.getMap(); validateHashMap(map); HashMap<String, OneDimensionalTestPojo> hashMap = pojo.getHashMap(); validateHashMap(hashMap); ConcurrentMap<String, OneDimensionalTestPojo> concurrentHashMap = pojo .getConcurrentHashMap(); validateConcurrentHashMap(concurrentHashMap); ConcurrentHashMap<String, OneDimensionalTestPojo> concurrentHashMapImpl = pojo .getConcurrentHashMapImpl(); validateConcurrentHashMap(concurrentHashMapImpl); Queue<SimplePojoToTestSetters> queue = pojo.getQueue(); Assert.assertNotNull("The queue cannot be null!", queue); Assert.assertTrue("The queue must be an instance of LinkedList", queue instanceof LinkedList); SimplePojoToTestSetters pojoQueueElement = queue.poll(); Assert.assertNotNull("The queue element cannot be null!", pojoQueueElement); @SuppressWarnings("rawtypes") List nonGenerifiedList = pojo.getNonGenerifiedList(); Assert.assertNotNull("The non generified list cannot be null!", nonGenerifiedList); Assert.assertFalse("The non-generified list cannot be empty!", nonGenerifiedList.isEmpty()); Map nonGenerifiedMap = pojo.getNonGenerifiedMap(); Assert.assertNotNull("The non generified map cannot be null!", nonGenerifiedMap); Assert.assertFalse("The non generified Map cannot be empty!", nonGenerifiedMap.isEmpty()); Object object = nonGenerifiedMap.get(nonGenerifiedMap.keySet() .iterator().next()); Assert.assertNotNull( "The object element within the Map cannot be null!", object); } @Test public void testPojoWithNoSettersAndCollectionInConstructor() { NoSetterWithCollectionInConstructorPojo pojo = factory .manufacturePojo(NoSetterWithCollectionInConstructorPojo.class); Assert.assertNotNull("The POJO cannot be null!", pojo); List<String> strList = pojo.getStrList(); Assert.assertNotNull( "The collection of Strings in the constructor cannot be null!", strList); Assert.assertFalse( "The collection of Strings in the constructor cannot be empty!", strList.isEmpty()); String strElement = strList.get(0); Assert.assertNotNull("The collection element cannot be null!", strElement); int intField = pojo.getIntField(); Assert.assertTrue( "The int field in the constructor must be different from zero", intField != 0); } @Test public void testByteValueAnnotation() { ByteValuePojo pojo = factory.manufacturePojo(ByteValuePojo.class); Assert.assertNotNull("The Pojo cannot be null!", pojo); byte byteFieldWithMinValueOnly = pojo.getByteFieldWithMinValueOnly(); Assert.assertTrue( "The byte field with min value only should have a minimum value of zero!", byteFieldWithMinValueOnly >= PodamTestConstants.NUMBER_INT_MIN_VALUE); byte byteFieldWithMaxValueOnly = pojo.getByteFieldWithMaxValueOnly(); Assert.assertTrue( "The byte field value cannot be greater than: " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, byteFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); byte byteFieldWithMinAndMaxValue = pojo .getByteFieldWithMinAndMaxValue(); Assert.assertTrue( "The byte field value must be between: " + PodamTestConstants.NUMBER_INT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, byteFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_INT_MIN_VALUE && byteFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); Byte byteObjectFieldWithMinValueOnly = pojo .getByteObjectFieldWithMinValueOnly(); Assert.assertNotNull( "The byte object with min value only cannot be null!", byteObjectFieldWithMinValueOnly); Assert.assertTrue( "The byte object value must be greate or equal than: " + PodamTestConstants.NUMBER_INT_MIN_VALUE, byteObjectFieldWithMinValueOnly >= PodamTestConstants.NUMBER_INT_MIN_VALUE); Byte byteObjectFieldWithMaxValueOnly = pojo .getByteObjectFieldWithMaxValueOnly(); Assert.assertNotNull("The byte object field cannot be null", byteObjectFieldWithMaxValueOnly); Assert.assertTrue( "The byte object field must have a value less or equal to " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, byteObjectFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); Byte byteObjectFieldWithMinAndMaxValue = pojo .getByteObjectFieldWithMinAndMaxValue(); Assert.assertNotNull("The byte object must not be null!", byteObjectFieldWithMinAndMaxValue); Assert.assertTrue( "The byte object must have a value between: " + PodamTestConstants.NUMBER_INT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_INT_MAX_VALUE, byteObjectFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_INT_MIN_VALUE && byteObjectFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_INT_MAX_VALUE); byte byteFieldWithPreciseValue = pojo.getByteFieldWithPreciseValue(); Assert.assertTrue("The byte with precise value should have value: " + PodamTestConstants.BYTE_PRECISE_VALUE, byteFieldWithPreciseValue == Byte .valueOf(PodamTestConstants.BYTE_PRECISE_VALUE)); } @Test(expected = PodamMockeryException.class) public void testByteAnnotationWithNumberFormatError() { factory.manufacturePojo(ByteValueWithErrorPojo.class); } @Test public void testShortValueAnnotation() { ShortValuePojo pojo = factory.manufacturePojo(ShortValuePojo.class); Assert.assertNotNull("The Pojo cannot be null!", pojo); short shortFieldWithMinValueOnly = pojo.getShortFieldWithMinValueOnly(); Assert.assertTrue( "The short attribute with min value only should have a value greater than " + PodamTestConstants.NUMBER_INT_MIN_VALUE, shortFieldWithMinValueOnly >= PodamTestConstants.NUMBER_INT_MIN_VALUE); short shortFieldWithMaxValueOnly = pojo.getShortFieldWithMaxValueOnly(); Assert.assertTrue( "The short attribute with max value only should have a value less than: " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, shortFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); short shortFieldWithMinAndMaxValue = pojo .getShortFieldWithMinAndMaxValue(); Assert.assertTrue( "The short field with min and max values should have a value beetween " + PodamTestConstants.NUMBER_INT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_INT_MAX_VALUE, shortFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_INT_MIN_VALUE && shortFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); Short shortObjectFieldWithMinValueOnly = pojo .getShortObjectFieldWithMinValueOnly(); Assert.assertNotNull( "The short object field with min value only should not be null!", shortObjectFieldWithMinValueOnly); Assert.assertTrue( "The short object attribute with min value only should have a value greater than " + PodamTestConstants.NUMBER_INT_MIN_VALUE, shortObjectFieldWithMinValueOnly >= PodamTestConstants.NUMBER_INT_MIN_VALUE); Short shortObjectFieldWithMaxValueOnly = pojo .getShortObjectFieldWithMaxValueOnly(); Assert.assertNotNull( "The short object field with max value only should not be null!", shortObjectFieldWithMaxValueOnly); Assert.assertTrue( "The short object attribute with max value only should have a value less than: " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, shortObjectFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); Short shortObjectFieldWithMinAndMaxValue = pojo .getShortObjectFieldWithMinAndMaxValue(); Assert.assertNotNull( "The short object field with max value only should not be null!", shortObjectFieldWithMinAndMaxValue); Assert.assertTrue( "The short object field with min and max values should have a value beetween " + PodamTestConstants.NUMBER_INT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, shortObjectFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_INT_MIN_VALUE && shortObjectFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); short shortFieldWithPreciseValue = pojo.getShortFieldWithPreciseValue(); Assert.assertTrue( "The short attribute with precise value should have a value of " + PodamTestConstants.SHORT_PRECISE_VALUE + " but instead it had a value of " + shortFieldWithPreciseValue, shortFieldWithPreciseValue == Short .valueOf(PodamTestConstants.SHORT_PRECISE_VALUE)); } @Test(expected = PodamMockeryException.class) public void testShortValueAnnotationWithNumberFormatException() { factory.manufacturePojo(ShortValueWithErrorPojo.class); } @Test public void testCharacterValueAnnotation() { CharValuePojo pojo = factory.manufacturePojo(CharValuePojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); char charFieldWithMinValueOnly = pojo.getCharFieldWithMinValueOnly(); Assert.assertTrue( "The char attribute with min value only should have a value greater than " + PodamTestConstants.NUMBER_INT_MIN_VALUE, charFieldWithMinValueOnly >= PodamTestConstants.NUMBER_INT_MIN_VALUE); char charFieldWithMaxValueOnly = pojo.getCharFieldWithMaxValueOnly(); Assert.assertTrue( "The char attribute with max value only should have a value less or equal than " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, charFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); char charFieldWithMinAndMaxValue = pojo .getCharFieldWithMinAndMaxValue(); Assert.assertTrue( "The char attribute with min and max value must have a value between " + PodamTestConstants.NUMBER_INT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, charFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_INT_MIN_VALUE && charFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); Character charObjectFieldWithMinValueOnly = pojo .getCharObjectFieldWithMinValueOnly(); Assert.assertNotNull( "The char object attribute with min value only cannot be null!", charObjectFieldWithMinValueOnly); Assert.assertTrue( "The char object attribute with min value only should have a value greater than " + PodamTestConstants.NUMBER_INT_MIN_VALUE, charObjectFieldWithMinValueOnly >= PodamTestConstants.NUMBER_INT_MIN_VALUE); Character charObjectFieldWithMaxValueOnly = pojo .getCharObjectFieldWithMaxValueOnly(); Assert.assertNotNull( "The char object attribute with max value only cannot be null!", charObjectFieldWithMaxValueOnly); Assert.assertTrue( "The char object attribute with max value only should have a value less or equal than " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, charObjectFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); Character charObjectFieldWithMinAndMaxValue = pojo .getCharObjectFieldWithMinAndMaxValue(); Assert.assertNotNull( "The char object attribute with min and max value cannot be null!", charObjectFieldWithMinAndMaxValue); Assert.assertTrue( "The char object attribute with min and max value must have a value between " + PodamTestConstants.NUMBER_INT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_INT_ONE_HUNDRED, charObjectFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_INT_MIN_VALUE && charObjectFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_INT_ONE_HUNDRED); char charFieldWithPreciseValue = pojo.getCharFieldWithPreciseValue(); Assert.assertTrue( "The character field with precise value should have a value of " + PodamTestConstants.CHAR_PRECISE_VALUE, charFieldWithPreciseValue == PodamTestConstants.CHAR_PRECISE_VALUE); char charFieldWithBlankInPreciseValue = pojo .getCharFieldWithBlankInPreciseValue(); Assert.assertTrue( "The value for the char field with an empty char in the precise value and no other annotation attributes should be zero", charFieldWithBlankInPreciseValue == 0); } @Test public void testBooleanValueAnnotation() { BooleanValuePojo pojo = factory.manufacturePojo(BooleanValuePojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); boolean boolDefaultToTrue = pojo.isBoolDefaultToTrue(); Assert.assertTrue( "The boolean attribute forced to true should be true!", boolDefaultToTrue); boolean boolDefaultToFalse = pojo.isBoolDefaultToFalse(); Assert.assertFalse( "The boolean attribute forced to false should be false!", boolDefaultToFalse); Boolean boolObjectDefaultToFalse = pojo.getBoolObjectDefaultToFalse(); Assert.assertNotNull( "The boolean object forced to false should not be null!", boolObjectDefaultToFalse); Assert.assertFalse( "The boolean object forced to false should have a value of false!", boolObjectDefaultToFalse); Boolean boolObjectDefaultToTrue = pojo.getBoolObjectDefaultToTrue(); Assert.assertNotNull( "The boolean object forced to true should not be null!", boolObjectDefaultToTrue); Assert.assertTrue( "The boolean object forced to true should have a value of true!", boolObjectDefaultToTrue); } @Test public void testFloatValueAnnotation() { FloatValuePojo pojo = factory.manufacturePojo(FloatValuePojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); float floatFieldWithMinValueOnly = pojo.getFloatFieldWithMinValueOnly(); Assert.assertTrue( "The float field with min value only must have value greater than " + PodamTestConstants.NUMBER_FLOAT_MIN_VALUE, floatFieldWithMinValueOnly >= PodamTestConstants.NUMBER_FLOAT_MIN_VALUE); float floatFieldWithMaxValueOnly = pojo.getFloatFieldWithMaxValueOnly(); Assert.assertTrue( "The float field with max value only can only have a value less or equal than " + PodamTestConstants.NUMBER_FLOAT_ONE_HUNDRED, floatFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_FLOAT_ONE_HUNDRED); float floatFieldWithMinAndMaxValue = pojo .getFloatFieldWithMinAndMaxValue(); Assert.assertTrue( "The float field with min and max value must have a value between " + PodamTestConstants.NUMBER_FLOAT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_FLOAT_MAX_VALUE, floatFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_FLOAT_MIN_VALUE && floatFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_FLOAT_MAX_VALUE); Float floatObjectFieldWithMinValueOnly = pojo .getFloatObjectFieldWithMinValueOnly(); Assert.assertNotNull( "The float object attribute with min value only cannot be null!", floatObjectFieldWithMinValueOnly); Assert.assertTrue( "The float object attribute with min value only must have a value greater or equal than " + PodamTestConstants.NUMBER_FLOAT_MIN_VALUE, floatObjectFieldWithMinValueOnly >= PodamTestConstants.NUMBER_FLOAT_MIN_VALUE); Float floatObjectFieldWithMaxValueOnly = pojo .getFloatObjectFieldWithMaxValueOnly(); Assert.assertNotNull( "The float object attribute with max value only cannot be null!", floatObjectFieldWithMaxValueOnly); Assert.assertTrue( "The float object attribute with max value only must have a value less than or equal to " + PodamTestConstants.NUMBER_FLOAT_ONE_HUNDRED, floatObjectFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_FLOAT_ONE_HUNDRED); Float floatObjectFieldWithMinAndMaxValue = pojo .getFloatObjectFieldWithMinAndMaxValue(); Assert.assertNotNull( "The float object attribute with min and max value cannot be null!", floatObjectFieldWithMinAndMaxValue); Assert.assertTrue( "The float object attribute with min and max value only must have a value between " + PodamTestConstants.NUMBER_FLOAT_MIN_VALUE + " and " + PodamTestConstants.NUMBER_FLOAT_MAX_VALUE, floatObjectFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_FLOAT_MIN_VALUE && floatObjectFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_FLOAT_MAX_VALUE); float floatFieldWithPreciseValue = pojo.getFloatFieldWithPreciseValue(); Assert.assertTrue( "The float field with precise value should have a value of " + PodamTestConstants.FLOAT_PRECISE_VALUE, floatFieldWithPreciseValue == Float .valueOf(PodamTestConstants.FLOAT_PRECISE_VALUE)); Float floatObjectFieldWithPreciseValue = pojo .getFloatObjectFieldWithPreciseValue(); Assert.assertNotNull( "The float object field with precise value cannot be null!", floatObjectFieldWithPreciseValue); Assert.assertTrue( "The float object field with precise value should have a value of " + PodamTestConstants.FLOAT_PRECISE_VALUE, floatObjectFieldWithPreciseValue.floatValue() == Float.valueOf( PodamTestConstants.FLOAT_PRECISE_VALUE).floatValue()); } @Test(expected = PodamMockeryException.class) public void testFloatValueAnnotationWithNumberFormatError() { factory.manufacturePojo(FloatValueWithErrorPojo.class); } @Test public void testDoubleValueAnnotation() { DoubleValuePojo pojo = factory.manufacturePojo(DoubleValuePojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); double doubleFieldWithMinValueOnly = pojo .getDoubleFieldWithMinValueOnly(); Assert.assertTrue( "The double attribute with min value only must have a value greater than " + PodamTestConstants.NUMBER_DOUBLE_MIN_VALUE, doubleFieldWithMinValueOnly >= PodamTestConstants.NUMBER_DOUBLE_MIN_VALUE); double doubleFieldWithMaxValueOnly = pojo .getDoubleFieldWithMaxValueOnly(); Assert.assertTrue( "The double attribute with max value only must have a value less or equal to " + PodamTestConstants.NUMBER_DOUBLE_ONE_HUNDRED, doubleFieldWithMaxValueOnly <= PodamTestConstants.NUMBER_DOUBLE_ONE_HUNDRED); double doubleFieldWithMinAndMaxValue = pojo .getDoubleFieldWithMinAndMaxValue(); Assert.assertTrue( "The double attribute with min and mx value must have a value between " + PodamTestConstants.NUMBER_DOUBLE_MIN_VALUE + " and " + PodamTestConstants.NUMBER_DOUBLE_MAX_VALUE, doubleFieldWithMinAndMaxValue >= PodamTestConstants.NUMBER_DOUBLE_MIN_VALUE && doubleFieldWithMinAndMaxValue <= PodamTestConstants.NUMBER_DOUBLE_MAX_VALUE); double doubleFieldWithPreciseValue = pojo .getDoubleFieldWithPreciseValue(); Assert.assertTrue( "The double field with precise value should have a value of: " + PodamTestConstants.DOUBLE_PRECISE_VALUE, doubleFieldWithPreciseValue == Double .valueOf(PodamTestConstants.DOUBLE_PRECISE_VALUE)); Double doubleObjectFieldWithPreciseValue = pojo .getDoubleObjectFieldWithPreciseValue(); Assert.assertNotNull( "The double object field with precise value cannot be null!", doubleObjectFieldWithPreciseValue); Assert.assertTrue( "The double object field with precise value should have a value of: " + PodamTestConstants.DOUBLE_PRECISE_VALUE, doubleObjectFieldWithPreciseValue.doubleValue() == Double .valueOf(PodamTestConstants.DOUBLE_PRECISE_VALUE) .doubleValue()); } @Test(expected = PodamMockeryException.class) public void testDoubleValueAnnotationWithError() { factory.manufacturePojo(DoubleValueWithErrorPojo.class); } @Test public void testStringValueAnnotation() { StringValuePojo pojo = factory.manufacturePojo(StringValuePojo.class); String twentyLengthString = pojo.getTwentyLengthString(); Assert.assertNotNull("The twentyLengthString cannot be null!", twentyLengthString); Assert.assertTrue( "The twenty length string must have a length of " + PodamTestConstants.STR_ANNOTATION_TWENTY_LENGTH + "! but it did have a length of " + twentyLengthString.length(), twentyLengthString.length() == PodamTestConstants.STR_ANNOTATION_TWENTY_LENGTH); String preciseValueString = pojo.getPreciseValueString(); Assert.assertNotNull("The precise value string cannot be null!", preciseValueString); Assert.assertEquals( "The expected and actual String values don't match", PodamTestConstants.STR_ANNOTATION_PRECISE_VALUE, preciseValueString); } @Test public void testCollectionAnnotation() { CollectionAnnotationPojo pojo = factory .manufacturePojo(CollectionAnnotationPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); List<String> strList = pojo.getStrList(); Assert.assertNotNull("The string list cannot be null!", strList); Assert.assertFalse("The string list cannot be empty!", strList.isEmpty()); Assert.assertTrue( "The string list must have " + PodamTestConstants.ANNOTATION_COLLECTION_NBR_ELEMENTS + " elements but it had only " + strList.size(), strList.size() == PodamTestConstants.ANNOTATION_COLLECTION_NBR_ELEMENTS); String[] strArray = pojo.getStrArray(); Assert.assertNotNull("The array cannot be null!", strArray); Assert.assertFalse("The array cannot be empty!", strArray.length == 0); Assert.assertTrue( "The number of elements in the array (" + strArray.length + ") does not match " + PodamTestConstants.ANNOTATION_COLLECTION_NBR_ELEMENTS, strArray.length == PodamTestConstants.ANNOTATION_COLLECTION_NBR_ELEMENTS); Map<String, String> stringMap = pojo.getStringMap(); Assert.assertNotNull("The map cannot be null!", stringMap); Assert.assertFalse("The map of strings cannot be empty!", stringMap.isEmpty()); Assert.assertTrue( "The number of elements in the map (" + stringMap.size() + ") does not match " + PodamTestConstants.ANNOTATION_COLLECTION_NBR_ELEMENTS, stringMap.size() == PodamTestConstants.ANNOTATION_COLLECTION_NBR_ELEMENTS); } @Test public void testImmutablePojoWithNonGenericCollections() { ImmutableWithNonGenericCollectionsPojo pojo = factory .manufacturePojo(ImmutableWithNonGenericCollectionsPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); @SuppressWarnings("unchecked") Collection<Object> nonGenerifiedCollection = pojo .getNonGenerifiedCollection(); Assert.assertNotNull("The non-generified collection cannot be null!", nonGenerifiedCollection); Assert.assertFalse("The non-generified collection cannot be empty!", nonGenerifiedCollection.isEmpty()); Assert.assertTrue( "The number of elements in the collection: " + nonGenerifiedCollection.size() + " does not match the expected value: " + ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS, nonGenerifiedCollection.size() == ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS); @SuppressWarnings("unchecked") Set<Object> nonGenerifiedSet = pojo.getNonGenerifiedSet(); Assert.assertNotNull("The non-generified Set cannot be null!", nonGenerifiedSet); Assert.assertFalse("The non-generified Set cannot be empty!", nonGenerifiedSet.isEmpty()); Assert.assertTrue( "The number of elements in the Set: " + nonGenerifiedSet.size() + " does not match the expected value: " + ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS, nonGenerifiedSet.size() == ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS); @SuppressWarnings("unchecked") Map<Object, Object> nonGenerifiedMap = pojo.getNonGenerifiedMap(); Assert.assertNotNull("The non-generified map cannot be null!", nonGenerifiedMap); Assert.assertFalse("The non generified map cannot be empty!", nonGenerifiedMap.isEmpty()); Assert.assertTrue( "The number of elements in the map: " + nonGenerifiedMap.size() + " does not match the expected value: " + ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS, nonGenerifiedMap.size() == ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS); } @Test public void testImmutablePojoWithGenerifiedCollectionsInConstructor() { ImmutableWithGenericCollectionsPojo pojo = factory .manufacturePojo(ImmutableWithGenericCollectionsPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Collection<OneDimensionalTestPojo> generifiedCollection = pojo .getGenerifiedCollection(); Assert.assertNotNull("The generified collection cannot be null!", generifiedCollection); Assert.assertFalse("The generified collection cannot be empty!", generifiedCollection.isEmpty()); Assert.assertTrue( "The number of elements in the generified collection: " + generifiedCollection.size() + " does not match the expected value: " + ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS, generifiedCollection.size() == ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS); Map<String, Calendar> generifiedMap = pojo.getGenerifiedMap(); Assert.assertNotNull("The generified map cannot be null!", generifiedMap); Assert.assertFalse("The generified map cannot be empty!", generifiedMap.isEmpty()); Assert.assertTrue( "The number of elements in the generified map: " + generifiedMap.size() + " does not match the expected value: " + ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS, generifiedMap.size() == ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS); Set<ImmutableWithNonGenericCollectionsPojo> generifiedSet = pojo .getGenerifiedSet(); Assert.assertNotNull("The generified set cannot be null!", generifiedSet); Assert.assertFalse("The generified set cannot be empty!", generifiedSet.isEmpty()); Assert.assertTrue( "The number of elements in the generified set: " + generifiedSet.size() + " does not match the expected value: " + ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS, generifiedSet.size() == ImmutableWithNonGenericCollectionsPojo.NBR_ELEMENTS); } @Test public void testSingletonWithParametersInPublicStaticMethod() { SingletonWithParametersInStaticFactoryPojo pojo = factory .manufacturePojo(SingletonWithParametersInStaticFactoryPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Assert.assertNotNull("The calendar object cannot be null!", pojo.getCreateDate()); Assert.assertNotNull("The first name cannot be null!", pojo.getFirstName()); List<OneDimensionalTestPojo> pojoList = pojo.getPojoList(); Assert.assertNotNull("The pojo list cannot be null!", pojoList); Assert.assertFalse("The pojo list cannot be empty", pojoList.isEmpty()); Map<String, OneDimensionalTestPojo> pojoMap = pojo.getPojoMap(); Assert.assertNotNull("The pojo map cannot be null!", pojoMap); Assert.assertFalse("The pojo map cannot be empty!", pojoMap.isEmpty()); } @Test public void testEnumsPojo() { EnumsPojo pojo = factory.manufacturePojo(EnumsPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); ExternalRatePodamEnum ratePodamExternal = pojo.getRatePodamExternal(); Assert.assertNotNull("The external enum attribute cannot be null!", ratePodamExternal); RatePodamInternal ratePodamInternal = pojo.getRatePodamInternal(); // Can't test for equality since internal enum is not visible Assert.assertNotNull("The internal enum cannot be null!", ratePodamInternal); } @Test public void testPodamStrategyValueAnnotation() { PodamStrategyPojo pojo = factory .manufacturePojo(PodamStrategyPojo.class); Assert.assertNotNull("The post code pojo cannot be null!", pojo); String postCode = pojo.getPostCode(); Assert.assertNotNull("The post code cannot be null!", postCode); Assert.assertEquals("The post code does not match the expected value", PodamTestConstants.POST_CODE, postCode); Calendar expectedBirthday = PodamTestUtils.getMyBirthday(); Calendar myBirthday = pojo.getMyBirthday(); Assert.assertEquals( "The expected and actual calendar objects are not the same", expectedBirthday.getTime(), myBirthday.getTime()); List<Calendar> myBirthdays = pojo.getMyBirthdays(); Assert.assertNotNull("The birthdays collection cannot be null!", myBirthdays); Assert.assertFalse("The birthdays collection cannot be empty!", myBirthdays.isEmpty()); for (Calendar birthday : myBirthdays) { Assert.assertEquals( "The expected birthday element does not match the actual", expectedBirthday.getTime(), birthday.getTime()); } Calendar[] myBirthdaysArray = pojo.getMyBirthdaysArray(); Assert.assertNotNull("The birthdays array cannot be null!", myBirthdaysArray); Assert.assertFalse("The birthdays array cannot be empty!", myBirthdaysArray.length == 0); for (Calendar birthday : myBirthdaysArray) { Assert.assertEquals( "The expected birthday element does not match the actual", expectedBirthday.getTime(), birthday.getTime()); } List<Object> objectList = pojo.getObjectList(); Assert.assertNotNull("The list of objects cannot be null!", objectList); Assert.assertFalse("The list of objects cannot be empty!", objectList.isEmpty()); Object[] myObjectArray = pojo.getMyObjectArray(); Assert.assertNotNull("The array of objects cannot be null!", myObjectArray); Assert.assertTrue("The array of objects cannot be empty", myObjectArray.length > 0); @SuppressWarnings("rawtypes") List nonGenericObjectList = pojo.getNonGenericObjectList(); Assert.assertNotNull("The non generified object list cannot be null!", nonGenericObjectList); Assert.assertFalse("The non generified object list cannot be empty!", nonGenericObjectList.isEmpty()); Map<String, Calendar> myBirthdaysMap = pojo.getMyBirthdaysMap(); Assert.assertNotNull("The birthday map cannot be null!", myBirthdaysMap); Assert.assertFalse("The birthday map cannot be empty!", myBirthdaysMap.isEmpty()); Set<String> keySet = myBirthdaysMap.keySet(); for (String key : keySet) { Assert.assertEquals("The map element is not my birthday!", expectedBirthday.getTime(), myBirthdaysMap.get(key) .getTime()); } } @Test(expected = PodamMockeryException.class) public void testStringPojoWithWrongTypeForAnnotationStrategy() { factory.manufacturePojo(StringWithWrongStrategyTypePojo.class); } @Test public void testPrivateOnlyConstructorPojo() { PrivateOnlyConstructorPojo pojo = factory .manufacturePojo(PrivateOnlyConstructorPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Assert.assertNotNull("The string attribute in pojo cannot be null!", pojo.getFirstName()); Assert.assertTrue("The int field in pojo cannot be zero!", pojo.getIntField() != 0); } @Test public void testNoDefaultPublicConstructorPojo() { NoDefaultPublicConstructorPojo pojo = factory .manufacturePojo(NoDefaultPublicConstructorPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Assert.assertNotNull("The string field cannot be null!", pojo.getFirstName()); Assert.assertTrue("The int field cannot be zero!", pojo.getIntField() != 0); } @Test public void testProtectedNonDefaultConstructorPojo() { ProtectedNonDefaultConstructorPojo pojo = factory .manufacturePojo(ProtectedNonDefaultConstructorPojo.class); Assert.assertNotNull("The pojo cannot be null!", pojo); Assert.assertNotNull("The string attribute cannot be null!", pojo.getFirstName()); Assert.assertTrue("The int field cannot be zero!", pojo.getIntField() != 0); } @Test public void testSomeJavaNativeClasses() { String pojo = factory.manufacturePojo(String.class); Assert.assertNotNull("The generated String object cannot be null!", pojo); Integer integerPojo = factory.manufacturePojo(Integer.class); Assert.assertNotNull("The integer pojo cannot be null!", integerPojo); Calendar calendarPojo = factory .manufacturePojo(GregorianCalendar.class); Assert.assertNotNull("The calendar pojo cannot be null", calendarPojo); Date datePojo = factory.manufacturePojo(Date.class); Assert.assertNotNull("The date pojo cannot be null!", datePojo); BigDecimal bigDecimalPojo = factory.manufacturePojo(BigDecimal.class); Assert.assertNotNull("The Big decimal pojo cannot be null!", bigDecimalPojo); } /** * It checks that the Calendar instance is valid * <p> * If the calendar returns a valid date then it's a valid instance * </p> * * @param calendarField * The calendar instance to check */ private void checkCalendarIsValid(Calendar calendarField) { Assert.assertNotNull("The Calendar field cannot be null", calendarField); Date calendarDate = calendarField.getTime(); Assert.assertNotNull("It appears the Calendar field is not valid", calendarDate); } /** * It validates that the returned list contains the expected values * * @param list * The list to verify */ private void validateReturnedList(List<String> list) { Assert.assertNotNull("The List<String> should not be null!", list); Assert.assertFalse("The List<String> cannot be empty!", list.isEmpty()); String element = list.get(0); Assert.assertNotNull( "The List<String> must have a non-null String element", element); } /** * It validates that the returned list contains the expected values * * @param set * The set to verify */ private void validateReturnedSet(Set<String> set) { Assert.assertNotNull("The Set<String> should not be null!", set); Assert.assertFalse("The Set<String> cannot be empty!", set.isEmpty()); String element = set.iterator().next(); Assert.assertNotNull( "The Set<String> must have a non-null String element", element); } /** * It validates the {@link HashMap} returned by Podam * * @param map * the map to be validated */ private void validateHashMap(Map<String, OneDimensionalTestPojo> map) { Assert.assertTrue("The map attribute must be of type HashMap", map instanceof HashMap); Assert.assertNotNull("The map object in the POJO cannot be null", map); Set<String> keySet = map.keySet(); Assert.assertNotNull("The Map must have at least one element", keySet); validateMapElement(map, keySet); } /** * It validates the concurrent hash map returned by podam * * @param map */ private void validateConcurrentHashMap( ConcurrentMap<String, OneDimensionalTestPojo> map) { Assert.assertTrue( "The map attribute must be of type ConcurrentHashMap", map instanceof ConcurrentHashMap); Assert.assertNotNull("The map object in the POJO cannot be null", map); Set<String> keySet = map.keySet(); Assert.assertNotNull("The Map must have at least one element", keySet); validateMapElement(map, keySet); } /** * It validates a map element * * @param map * The Map to validate * @param keySet * The Set of keys in the map */ private void validateMapElement(Map<String, OneDimensionalTestPojo> map, Set<String> keySet) { OneDimensionalTestPojo oneDimensionalTestPojo = map.get(keySet .iterator().next()); Assert.assertNotNull("The map element must not be null!", oneDimensionalTestPojo); } }
package uk.gov.verifiablelog.merkletree; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.function.Function; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static uk.gov.verifiablelog.merkletree.TestUtil.*; @RunWith(Parameterized.class) public class MerkleTreeTests { public static final List<byte[]> TEST_INPUTS = Arrays.asList( new byte[]{}, new byte[]{0x00}, new byte[]{0x10}, new byte[]{0x20, 0x21}, new byte[]{0x30, 0x31}, new byte[]{0x40, 0x41, 0x42, 0x43}, new byte[]{0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57}, new byte[]{0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f}); private static final String emptyRootHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; private final Function<List<byte[]>, MerkleTree> makeMerkleTreeFn; private List<byte[]> leafValues; private MerkleTree merkleTree; public MerkleTreeTests(Function<List<byte[]>, MerkleTree> makeMerkleTreeFn) { this.leafValues = new ArrayList(); this.makeMerkleTreeFn = makeMerkleTreeFn; } @Parameters(name = "case: {index}") public static Collection<Function<List<byte[]>, MerkleTree>> data() { return Arrays.asList( leafValues -> makeMerkleTree(leafValues), leafValues -> makeMerkleTree(leafValues, null), leafValues -> makeMerkleTree(leafValues, new InMemory()), leafValues -> makeMerkleTree(leafValues, new InMemoryPowOfTwo()) ); } @Before public void beforeEach() throws NoSuchAlgorithmException { leafValues.clear(); merkleTree = makeMerkleTreeFn.apply(leafValues); } @Test public void expectedRootFromEmptyMerkleTree() { assertThat(bytesToString(merkleTree.currentRoot()), is(emptyRootHash)); } @Test public void expectedRootFromMerkleTreeWithLeavesForTree() { leafValues.add(TEST_INPUTS.get(0)); assertThat(bytesToString(merkleTree.currentRoot()), is("6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d")); leafValues.add(TEST_INPUTS.get(1)); assertThat(bytesToString(merkleTree.currentRoot()), is("fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125")); leafValues.add(TEST_INPUTS.get(2)); assertThat(bytesToString(merkleTree.currentRoot()), is("aeb6bcfe274b70a14fb067a5e5578264db0fa9b51af5e0ba159158f329e06e77")); leafValues.add(TEST_INPUTS.get(3)); assertThat(bytesToString(merkleTree.currentRoot()), is("d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7")); leafValues.add(TEST_INPUTS.get(4)); assertThat(bytesToString(merkleTree.currentRoot()), is("4e3bbb1f7b478dcfe71fb631631519a3bca12c9aefca1612bfce4c13a86264d4")); leafValues.add(TEST_INPUTS.get(5)); assertThat(bytesToString(merkleTree.currentRoot()), is("76e67dadbcdf1e10e1b74ddc608abd2f98dfb16fbce75277b5232a127f2087ef")); leafValues.add(TEST_INPUTS.get(6)); assertThat(bytesToString(merkleTree.currentRoot()), is("ddb89be403809e325750d3d263cd78929c2942b7942a34b77e122c9594a74c8c")); leafValues.add(TEST_INPUTS.get(7)); assertThat(bytesToString(merkleTree.currentRoot()), is("5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328")); } @Test public void expectedAuditPathForSnapshotSize() { for (byte[] testInput : TEST_INPUTS) { leafValues.add(testInput); } List<byte[]> auditPath1 = merkleTree.pathToRootAtSnapshot(0, 0); assertThat(auditPath1.size(), is(0)); List<byte[]> auditPath2 = merkleTree.pathToRootAtSnapshot(0, 1); assertThat(auditPath2.size(), is(0)); List<byte[]> auditPath3 = merkleTree.pathToRootAtSnapshot(0, 8); assertThat(bytesToString(auditPath3), is(Arrays.asList( "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7", "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4"))); List<byte[]> auditPath4 = merkleTree.pathToRootAtSnapshot(5, 8); assertThat(bytesToString(auditPath4), is(Arrays.asList( "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b", "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0", "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7"))); List<byte[]> auditPath5 = merkleTree.pathToRootAtSnapshot(2, 3); assertThat(bytesToString(auditPath5), is(Arrays.asList( "fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125"))); List<byte[]> auditPath6 = merkleTree.pathToRootAtSnapshot(1, 5); assertThat(bytesToString(auditPath6), is(Arrays.asList( "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d", "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b"))); } @Test public void expectedConsistencySetForSnapshots() { for (byte[] testInput : TEST_INPUTS) { leafValues.add(testInput); } List<byte[]> consistencySet1 = merkleTree.snapshotConsistency(1, 1); assertThat(consistencySet1.size(), is(0)); List<byte[]> consistencySet2 = merkleTree.snapshotConsistency(1, 8); assertThat(bytesToString(consistencySet2), is(Arrays.asList( "96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7", "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4"))); List<byte[]> consistencySet3 = merkleTree.snapshotConsistency(6, 8); assertThat(bytesToString(consistencySet3), is(Arrays.asList( "0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a", "ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0", "d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7"))); List<byte[]> consistencySet4 = merkleTree.snapshotConsistency(2, 5); assertThat(bytesToString(consistencySet4), is(Arrays.asList( "5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e", "bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b"))); } }
package com.intellij.ui; import com.intellij.diagnostic.Activity; import com.intellij.diagnostic.ActivitySubNames; import com.intellij.diagnostic.ParallelActivity; import com.intellij.icons.AllIcons; import com.intellij.ide.BrowserUtil; import com.intellij.ide.gdpr.Consent; import com.intellij.ide.gdpr.ConsentOptions; import com.intellij.ide.gdpr.ConsentSettingsUi; import com.intellij.ide.gdpr.EndUserAgreement; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.idea.Main; import com.intellij.idea.SplashManager; import com.intellij.internal.statistic.persistence.UsageStatisticsPersistenceComponent; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.ui.AppIcon.MacAppIcon; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.JBImageIcon; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.JBUIScale.ScaleContext; import com.intellij.util.ui.SwingHelper; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import sun.awt.AWTAccessor; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.HyperlinkEvent; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.StyleSheet; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER; import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; /** * @author yole */ public class AppUIUtil { private static final String VENDOR_PREFIX = "jetbrains-"; private static final boolean RUNNING_FROM_SOURCES = PluginManagerCore.isRunningFromSources(); private static List<Image> ourIcons = null; private static boolean ourMacDocIconSet = false; @NotNull private static Logger getLogger() { return Logger.getInstance(AppUIUtil.class); } public static void updateWindowIcon(@NotNull Window window) { if (isWindowIconAlreadyExternallySet()) { return; } List<Image> images = ourIcons; if (images == null) { ourIcons = images = new ArrayList<>(3); ApplicationInfoEx appInfo = ApplicationInfoImpl.getShadowInstance(); String svgIconUrl = appInfo.getApplicationSvgIconUrl(); ScaleContext ctx = ScaleContext.create(window); if (SystemInfoRt.isUnix) { @SuppressWarnings("deprecation") String fallback = appInfo.getBigIconUrl(); ContainerUtil.addIfNotNull(images, loadApplicationIconImage(svgIconUrl, ctx, 128, fallback)); } @SuppressWarnings("deprecation") String fallback = appInfo.getIconUrl(); ContainerUtil.addIfNotNull(images, loadApplicationIconImage(svgIconUrl, ctx, 32, fallback)); if (SystemInfoRt.isWindows) { ContainerUtil.addIfNotNull(images, loadSmallApplicationIconImage(ctx)); } for (int i = 0; i < images.size(); i++) { Image image = images.get(i); if (image instanceof JBHiDPIScaledImage) { images.set(i, ((JBHiDPIScaledImage)image).getDelegate()); } } } if (!images.isEmpty()) { if (!SystemInfoRt.isMac) { window.setIconImages(images); } else if (RUNNING_FROM_SOURCES && !ourMacDocIconSet) { MacAppIcon.setDockIcon(ImageUtil.toBufferedImage(images.get(0))); ourMacDocIconSet = true; } } } public static boolean isWindowIconAlreadyExternallySet() { if (SystemInfoRt.isMac) { return !RUNNING_FROM_SOURCES; } // todo[tav] 'jbre.win.app.icon.supported' is defined by JBRE, remove when OpenJDK supports it as well return SystemInfoRt.isWindows && Boolean.getBoolean("ide.native.launcher") && Boolean.getBoolean("jbre.win.app.icon.supported"); } @NotNull private static Image loadSmallApplicationIconImage(@NotNull ScaleContext ctx) { ApplicationInfoEx appInfo = ApplicationInfoImpl.getShadowInstance(); @SuppressWarnings("deprecation") String fallbackSmallIconUrl = appInfo.getSmallIconUrl(); return loadApplicationIconImage(appInfo.getSmallApplicationSvgIconUrl(), ctx, 16, fallbackSmallIconUrl); } @NotNull public static Icon loadSmallApplicationIcon(@NotNull ScaleContext ctx) { Image image = loadSmallApplicationIconImage(ctx); return new JBImageIcon(ImageUtil.ensureHiDPI(image, ctx)); } @Contract("_, _, _, !null -> !null") @Nullable private static Image loadApplicationIconImage(String svgPath, ScaleContext ctx, int size, String fallbackPath) { if (svgPath != null) { try (InputStream stream = AppUIUtil.class.getResourceAsStream(svgPath)) { return SVGLoader.load(null, stream, ctx, size, size); } catch (IOException e) { getLogger().info("Cannot load SVG application icon from " + svgPath, e); } } if (fallbackPath != null) { return ImageLoader.loadFromResource(fallbackPath); } return null; } public static void invokeLaterIfProjectAlive(@NotNull Project project, @NotNull Runnable runnable) { Application application = ApplicationManager.getApplication(); if (application.isDispatchThread()) { runnable.run(); } else { application.invokeLater(runnable, o -> !project.isOpen() || project.isDisposed()); } } public static void invokeOnEdt(Runnable runnable) { invokeOnEdt(runnable, null); } public static void invokeOnEdt(Runnable runnable, @Nullable Condition<?> expired) { Application application = ApplicationManager.getApplication(); if (application.isDispatchThread()) { if (expired == null || !expired.value(null)) { runnable.run(); } } else if (expired == null) { application.invokeLater(runnable); } else { application.invokeLater(runnable, expired); } } public static void updateFrameClass(@NotNull Toolkit toolkit) { if (SystemInfoRt.isWindows || SystemInfoRt.isMac) { return; } Activity activity = ParallelActivity.PREPARE_APP_INIT.start(ActivitySubNames.UPDATE_FRAME_CLASS); try { Class<? extends Toolkit> aClass = toolkit.getClass(); if ("sun.awt.X11.XToolkit".equals(aClass.getName())) { ReflectionUtil.setField(aClass, toolkit, null, "awtAppClassName", getFrameClass()); } } catch (Exception ignore) { } activity.end(); } // keep in sync with LinuxDistributionBuilder#getFrameClass public static String getFrameClass() { String name = StringUtil.toLowerCase(ApplicationNamesInfo.getInstance().getFullProductNameWithEdition()) .replace(' ', '-') .replace("intellij-idea", "idea").replace("android-studio", "studio") // backward compatibility .replace("-community-edition", "-ce").replace("-ultimate-edition", "").replace("-professional-edition", ""); String wmClass = name.startsWith(VENDOR_PREFIX) ? name : VENDOR_PREFIX + name; if (RUNNING_FROM_SOURCES) wmClass += "-debug"; return wmClass; } public static void registerBundledFonts() { if (!SystemProperties.getBooleanProperty("ide.register.bundled.fonts", true)) { return; } Activity activity = ParallelActivity.PREPARE_APP_INIT.start(ActivitySubNames.REGISTER_BUNDLED_FONTS); File fontDir = PluginManagerCore.isRunningFromSources() ? new File(PathManager.getCommunityHomePath(), "platform/platform-resources/src/fonts") : null; registerFont("Inconsolata.ttf", fontDir); registerFont("SourceCodePro-Regular.ttf", fontDir); registerFont("SourceCodePro-Bold.ttf", fontDir); registerFont("SourceCodePro-It.ttf", fontDir); registerFont("SourceCodePro-BoldIt.ttf", fontDir); registerFont("FiraCode-Regular.ttf", fontDir); registerFont("FiraCode-Bold.ttf", fontDir); registerFont("FiraCode-Light.ttf", fontDir); registerFont("FiraCode-Medium.ttf", fontDir); registerFont("FiraCode-Retina.ttf", fontDir); activity.end(); } private static void registerFont(@NotNull String name, @Nullable File fontDir) { try { Font font; if (fontDir == null) { URL url = AppUIUtil.class.getResource("/fonts/" + name); if (url == null) { getLogger().warn("Resource missing: " + name); return; } try (InputStream is = url.openStream()) { font = Font.createFont(Font.TRUETYPE_FONT, is); } } else { font = Font.createFont(Font.TRUETYPE_FONT, new File(fontDir, name)); } GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); } catch (Throwable t) { getLogger().warn("Cannot register font: " + name, t); } } public static void hideToolWindowBalloon(@NotNull String id, @NotNull Project project) { invokeLaterIfProjectAlive(project, () -> { Balloon balloon = ToolWindowManager.getInstance(project).getToolWindowBalloon(id); if (balloon != null) { balloon.hide(); } }); } private static final int MIN_ICON_SIZE = 32; @Nullable public static String findIcon() { String iconsPath = PathManager.getBinPath(); String[] childFiles = ObjectUtils.notNull(new File(iconsPath).list(), ArrayUtilRt.EMPTY_STRING_ARRAY); // 1. look for .svg icon for (String child : childFiles) { if (child.endsWith(".svg")) { return iconsPath + '/' + child; } } File svgFile = ApplicationInfoEx.getInstanceEx().getApplicationSvgIconFile(); if (svgFile != null) { return svgFile.getAbsolutePath(); } // 2. look for .png icon of max size int best = MIN_ICON_SIZE - 1; String iconPath = null; for (String child : childFiles) { if (child.endsWith(".png")) { String path = iconsPath + '/' + child; Icon icon = new ImageIcon(path); int size = icon.getIconHeight(); if (size > best && size == icon.getIconWidth()) { best = size; iconPath = path; } } } return iconPath; } public static void showUserAgreementAndConsentsIfNeeded(@NotNull Logger log) { if (ApplicationInfoImpl.getShadowInstance().isVendorJetBrains()) { EndUserAgreement.updateCachedContentToLatestBundledVersion(); EndUserAgreement.Document agreement = EndUserAgreement.getLatestDocument(); if (!agreement.isAccepted()) { try { // todo: does not seem to request focus when shown EventQueue.invokeAndWait(() -> { SplashManager.setVisible(false); showEndUserAgreementText(agreement.getText(), agreement.isPrivacyPolicy()); SplashManager.setVisible(true); }); EndUserAgreement.setAccepted(agreement); } catch (Exception e) { log.warn(e); } } showConsentsAgreementIfNeeded(log); } } /** @deprecated use {@link #showUserAgreementAndConsentsIfNeeded(Logger)} instead */ @Deprecated public static boolean showConsentsAgreementIfNeed(@NotNull Logger log) { return showConsentsAgreementIfNeeded(log); } public static boolean showConsentsAgreementIfNeeded(@NotNull Logger log) { final Pair<List<Consent>, Boolean> consentsToShow = ConsentOptions.getInstance().getConsents(); final Ref<Boolean> result = new Ref<>(Boolean.FALSE); if (consentsToShow.second) { Runnable runnable = () -> result.set(confirmConsentOptions(consentsToShow.first)); if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { try { SwingUtilities.invokeAndWait(runnable); } catch (Exception e) { log.warn(e); } } } return result.get(); } /** * todo: update to support GDPR requirements * * @param htmlText Updated version of Privacy Policy or EULA text if any. * If it's {@code null}, the standard text from bundled resources would be used. * @param isPrivacyPolicy true if this document is a privacy policy */ public static void showEndUserAgreementText(@NotNull String htmlText, final boolean isPrivacyPolicy) { DialogWrapper dialog = new DialogWrapper(true) { private JEditorPane myViewer; @Override protected JComponent createCenterPanel() { JPanel centerPanel = new JPanel(new BorderLayout(0, JBUI.scale(8))); myViewer = SwingHelper.createHtmlViewer(true, null, JBColor.WHITE, JBColor.BLACK); myViewer.setFocusable(true); myViewer.addHyperlinkListener(new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { URL url = e.getURL(); if (url != null) { BrowserUtil.browse(url); } else { SwingHelper.scrollToReference(myViewer, e.getDescription()); } } }); myViewer.setText(htmlText); StyleSheet styleSheet = ((HTMLDocument)myViewer.getDocument()).getStyleSheet(); styleSheet.addRule("body {font-family: \"Segoe UI\", Tahoma, sans-serif;}"); styleSheet.addRule("body {margin-top:0;padding-top:0;}"); styleSheet.addRule("body {font-size:" + JBUI.scaleFontSize(13) + "pt;}"); styleSheet.addRule("h2, em {margin-top:" + JBUI.scaleFontSize(20) + "pt;}"); styleSheet.addRule("h1, h2, h3, p, h4, em {margin-bottom:0;padding-bottom:0;}"); styleSheet.addRule("p, h1 {margin-top:0;padding-top:"+JBUI.scaleFontSize(6)+"pt;}"); styleSheet.addRule("li {margin-bottom:" + JBUI.scaleFontSize(6) + "pt;}"); styleSheet.addRule("h2 {margin-top:0;padding-top:"+JBUI.scaleFontSize(13)+"pt;}"); myViewer.setCaretPosition(0); myViewer.setBorder(JBUI.Borders.empty(0, 5, 5, 5)); centerPanel.add(JBUI.Borders.emptyTop(8).wrap( new JLabel("Please read and accept these terms and conditions. Scroll down for full text:")), BorderLayout.NORTH); JBScrollPane scrollPane = new JBScrollPane(myViewer, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER); centerPanel.add(scrollPane, BorderLayout.CENTER); JPanel bottomPanel = new JPanel(new BorderLayout()); if (ApplicationInfoImpl.getShadowInstance().isEAP()) { JPanel eapPanel = new JPanel(new BorderLayout(8, 8)); eapPanel.setBorder(JBUI.Borders.empty(8)); //noinspection UseJBColor eapPanel.setBackground(new Color(0xDCE4E8)); IconLoader.activate(); JLabel label = new JLabel(AllIcons.General.BalloonInformation); label.setVerticalAlignment(SwingConstants.TOP); eapPanel.add(label, BorderLayout.WEST); JEditorPane html = SwingHelper.createHtmlLabel( "EAP builds report usage statistics by default per "+ (isPrivacyPolicy? "this Privacy Policy." : "the <a href=\"https: "<br/>No personal or sensitive data are sent. You may disable this in the settings.", null, null ); eapPanel.add(html, BorderLayout.CENTER); bottomPanel.add(eapPanel, BorderLayout.NORTH); } JCheckBox checkBox = new JCheckBox("I confirm that I have read and accept the terms of this User Agreement"); bottomPanel.add(JBUI.Borders.empty(24, 0, 16, 0).wrap(checkBox), BorderLayout.CENTER); centerPanel.add(JBUI.Borders.emptyTop(8).wrap(bottomPanel), BorderLayout.SOUTH); checkBox.addActionListener(e -> setOKActionEnabled(checkBox.isSelected())); centerPanel.setPreferredSize(JBUI.size(500, 450)); return centerPanel; } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myViewer; } @Override protected void createDefaultActions() { super.createDefaultActions(); init(); setOKButtonText("Continue"); setOKActionEnabled(false); setCancelButtonText("Reject and Exit"); setAutoAdjustable(false); } @Override public void doCancelAction() { super.doCancelAction(); Application application = ApplicationManager.getApplication(); if (application == null) { System.exit(Main.PRIVACY_POLICY_REJECTION); } else { ((ApplicationImpl)application).exit(true, true, false); } } }; dialog.setModal(true); dialog.setTitle( isPrivacyPolicy ? ApplicationInfoImpl.getShadowInstance().getShortCompanyName() + " Privacy Policy" : ApplicationNamesInfo.getInstance().getFullProductName() + " User Agreement" ); dialog.pack(); dialog.show(); } public static boolean confirmConsentOptions(@NotNull List<Consent> consents) { if (consents.isEmpty()) { return false; } ConsentSettingsUi ui = new ConsentSettingsUi(false); final DialogWrapper dialog = new DialogWrapper(true) { @Nullable @Override protected Border createContentPaneBorder() { return null; } @Nullable @Override protected JComponent createSouthPanel() { JComponent southPanel = super.createSouthPanel(); if (southPanel != null) { southPanel.setBorder(ourDefaultBorder); } return southPanel; } @Override protected JComponent createCenterPanel() { return ui.getComponent(); } @NotNull @Override protected Action[] createActions() { if (consents.size() > 1) { Action[] actions = super.createActions(); setOKButtonText("Save"); setCancelButtonText("Skip"); return actions; } setOKButtonText(consents.iterator().next().getName()); return new Action[]{getOKAction(), new DialogWrapperAction("Don't send") { @Override protected void doAction(ActionEvent e) { close(NEXT_USER_EXIT_CODE); } }}; } @Override protected void createDefaultActions() { super.createDefaultActions(); init(); setAutoAdjustable(false); } }; ui.reset(consents); dialog.setModal(true); dialog.setTitle("Data Sharing"); dialog.pack(); if (consents.size() < 2) { dialog.setSize(dialog.getWindow().getWidth(), dialog.getWindow().getHeight() + JBUI.scale(75)); } dialog.show(); int exitCode = dialog.getExitCode(); if (exitCode == DialogWrapper.CANCEL_EXIT_CODE) { return false; //Don't save any changes in this case: user hasn't made a choice } final List<Consent> result; if (consents.size() == 1) { result = Collections.singletonList(consents.iterator().next().derive(exitCode == DialogWrapper.OK_EXIT_CODE)); } else { result = new ArrayList<>(); ui.apply(result); } saveConsents(result); return true; } public static List<Consent> loadConsentsForEditing() { final ConsentOptions options = ConsentOptions.getInstance(); List<Consent> result = options.getConsents().first; if (options.isEAP()) { final Consent statConsent = options.getUsageStatsConsent(); if (statConsent != null) { // init stats consent for EAP from the dedicated location final List<Consent> consents = result; result = new ArrayList<>(); result.add(statConsent.derive(UsageStatisticsPersistenceComponent.getInstance().isAllowed())); result.addAll(consents); } } return result; } public static void saveConsents(List<Consent> consents) { final ConsentOptions options = ConsentOptions.getInstance(); final Application app = ApplicationManager.getApplication(); List<Consent> toSave = consents; if (app != null && options.isEAP()) { final Consent defaultStatsConsent = options.getUsageStatsConsent(); if (defaultStatsConsent != null) { toSave = new ArrayList<>(); for (Consent consent : consents) { if (defaultStatsConsent.getId().equals(consent.getId())) { UsageStatisticsPersistenceComponent.getInstance().setAllowed(consent.isAccepted()); } else { toSave.add(consent); } } } } if (!toSave.isEmpty()) { options.setConsents(toSave); } } public static void targetToDevice(@NotNull Component comp, @Nullable Component target) { if (comp.isShowing()) return; GraphicsConfiguration gc = target != null ? target.getGraphicsConfiguration() : null; setGraphicsConfiguration(comp, gc); } public static void setGraphicsConfiguration(@NotNull Component comp, @Nullable GraphicsConfiguration gc) { AWTAccessor.getComponentAccessor().setGraphicsConfiguration(comp, gc); } }
// are permitted provided that the following conditions are met: // other materials provided with the distribution. // Neither the name of Nexage, PubNative nor the names of its // contributors may be used to endorse or promote products derived from // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package net.pubnative.player; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import net.pubnative.player.model.TRACKING_EVENTS_TYPE; import net.pubnative.player.model.VASTModel; import net.pubnative.player.util.HttpTools; import net.pubnative.player.util.VASTLog; import net.pubnative.player.widget.CountDownView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class VASTPlayer extends RelativeLayout implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, View.OnClickListener { //SurfaceHolder.Callback { private static final String TAG = VASTPlayer.class.getName(); private static final String TEXT_BUFFERING = "Buffering..."; /** * Player type will lead to different layouts and behaviour to improve campaign type */ public enum CampaignType { // Cost per click, this will improve player click possibilities CPC, // Cost per million (of impressions), this will improve impression behaviour (keep playing) CPM } /** * Callbacks for following the player behaviour */ public interface Listener { void onVASTPlayerLoadFinish(); void onVASTPlayerFail(Exception exception); void onVASTPlayerPlaybackStart(); void onVASTPlayerPlaybackFinish(); void onVASTPlayerOpenOffer(); } private enum PlayerState { Empty, Loading, Ready, Playing, Pause } // LISTENERS private Listener mListener = null; // TIMERS private Timer mLayoutTimer; private Timer mProgressTimer; private Timer mTrackingEventsTimer; private static final long TIMER_TRACKING_INTERVAL = 250; private static final long TIMER_PROGRESS_INTERVAL = 50; private static final long TIMER_LAYOUT_INTERVAL = 50; private static final int MAX_PROGRESS_TRACKING_POINTS = 20; // TRACKING private HashMap<TRACKING_EVENTS_TYPE, List<String>> mTrackingEventMap; // DATA private VASTModel mVastModel; private String mSkipName; private int mSkipDelay; // PLAYER private MediaPlayer mMediaPlayer; // VIEWS private View mRoot; private View mOpen; // Load private View mLoader; private TextView mLoaderText; // Player private View mPlayer; private SurfaceView mSurface; private TextView mSkip; private ImageView mMute; private CountDownView mCountDown; // Banner private ImageView mBanner; private View mPlay; // OTHERS private Bitmap mBannerBitmap = null; private Handler mMainHandler = null; private int mVideoHeight = 0; private int mVideoWidth = 0; private boolean mIsVideoMute = false; private boolean mIsBufferingShown = false; private boolean mIsDataSourceSet = false; private int mQuartile = 0; private CampaignType mCampaignType = CampaignType.CPM; private PlayerState mPlayerState = PlayerState.Empty; private List<Integer> mProgressTracker = null; private double mTargetAspect = -1.0; public VASTPlayer(Context context) { super(context); } public VASTPlayer(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * Sets the desired aspect ratio. The value is <code>width / height</code>. */ public void setAspectRatio(double aspectRatio) { if (aspectRatio < 0) { throw new IllegalArgumentException(); } Log.d(TAG, "Setting aspect ratio to " + aspectRatio + " (was " + mTargetAspect + ")"); if (mTargetAspect != aspectRatio) { mTargetAspect = aspectRatio; requestLayout(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Target aspect ratio will be < 0 if it hasn't been set yet. In that case, // we just use whatever we've been handed. if (mTargetAspect > 0) { int initialWidth = MeasureSpec.getSize(widthMeasureSpec); int initialHeight = MeasureSpec.getSize(heightMeasureSpec); // factor the padding out int horizPadding = getPaddingLeft() + getPaddingRight(); int vertPadding = getPaddingTop() + getPaddingBottom(); initialWidth -= horizPadding; initialHeight -= vertPadding; double viewAspectRatio = (double) initialWidth / initialHeight; double aspectDiff = mTargetAspect / viewAspectRatio - 1; if (Math.abs(aspectDiff) < 0.01) { // We're very close already. We don't want to risk switching from e.g. non-scaled // 1280x720 to scaled 1280x719 because of some floating-point round-off error, // so if we're really close just leave it alone. Log.v(TAG, "aspect ratio is good (target=" + mTargetAspect + ", view=" + initialWidth + "x" + initialHeight + ")"); } else { if (aspectDiff > 0) { // limited by narrow width; restrict height initialHeight = (int) (initialWidth / mTargetAspect); } else { // limited by short height; restrict width initialWidth = (int) (initialHeight * mTargetAspect); } Log.v(TAG, "new size=" + initialWidth + "x" + initialHeight + " + padding " + horizPadding + "x" + vertPadding); initialWidth += horizPadding; initialHeight += vertPadding; widthMeasureSpec = MeasureSpec.makeMeasureSpec(initialWidth, MeasureSpec.EXACTLY); heightMeasureSpec = MeasureSpec.makeMeasureSpec(initialHeight, MeasureSpec.EXACTLY); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } // State machine private boolean canSetState(PlayerState playerState) { boolean result = false; switch (playerState) { case Empty: result = true; break; case Loading: result = true; break; case Ready: result = (PlayerState.Loading == mPlayerState); break; case Playing: result = ((mPlayerState == PlayerState.Ready) || (mPlayerState == PlayerState.Pause)); break; case Pause: result = true; break; } return result; } /** * this method controls the associated state machine of the video player behaviour * * @param playerState state to set * @return */ private void setState(PlayerState playerState) { Log.v(TAG, "setState: " + playerState.name()); if (canSetState(playerState)) { switch (playerState) { case Empty: setEmptyState(); break; case Loading: setLoadingState(); break; case Ready: setReadyState(); break; case Playing: setPlayingState(); break; case Pause: setPauseState(); break; } mPlayerState = playerState; } } private void setEmptyState() { Log.v(TAG, "setEmptyState"); // Visual aspect total empty hideSurface(); hidePlayerLayout(); hidePlay(); hideOpen(); hideLoader(); hideBanner(); /** * Do not change this order, since cleaning the media player before invalidating timers * could make the timers threads access an invalid media player */ stopTimers(); cleanMediaPlayer(); // Reset all other items mIsDataSourceSet = false; mVastModel = null; mQuartile = 0; mTrackingEventMap = null; mProgressTracker = null; mBannerBitmap = null; } private void setLoadingState() { Log.v(TAG, "setLoadingState"); // Show loader if (isBannerReady()) { showBanner(); } else { hideBanner(); } hidePlay(); hidePlayerLayout(); showOpen(); showSurface(); showLoader(""); mTrackingEventMap = mVastModel.getTrackingUrls(); createMediaPlayer(); turnVolumeOff(); startCaching(); } private void setReadyState() { Log.v(TAG, "setReadyState"); hideLoader(); hidePlayerLayout(); if (isBannerReady()) { showBanner(); } else { hideBanner(); } showOpen(); showPlay(); showSurface(); turnVolumeOff(); } private void setPlayingState() { Log.v(TAG, "setPlayingState"); hideBanner(); hidePlay(); hideLoader(); showOpen(); showSurface(); showPlayerLayout(); /** * Don't change the order of this, since starting the media player after te timers could * lead to an invalid mediaplayer required inside the timers. */ if (mSurface != null && mSurface.getHolder() != null) { final Surface surface = mSurface.getHolder().getSurface(); if ( surface.isValid() ) { mMediaPlayer.setDisplay(mSurface.getHolder()); } } calculateAspectRatio(); refreshVolume(); mMediaPlayer.start(); startTimers(); } private void setPauseState() { Log.v(TAG, "setPauseState"); hideLoader(); hidePlayerLayout(); if (isBannerReady()) { showBanner(); } else { hideBanner(); } showOpen(); showPlay(); showSurface(); turnVolumeOff(); refreshVolume(); } // PUBLIC /** * Constructor, generally used automatically by a layout inflater * * @param context * @param attrs */ public VASTPlayer(Context context, AttributeSet attrs) { super(context, attrs); mMainHandler = new Handler(getContext().getMainLooper()); createLayout(); setEmptyState(); } /** * Sets listener for callbacks related to status of player * * @param listener Listener */ public void setListener(Listener listener) { Log.v(TAG, "setListener"); mListener = listener; } /** * sets the banner that would be displayed after video * * @param bitmap valid bitmap */ public void setBanner(Bitmap bitmap) { mBannerBitmap = bitmap; if (mBannerBitmap == null) { mBanner.setImageResource(0); } else { mBanner.setImageBitmap(mBannerBitmap); } } /** * Sets the campaign type of the player * * @param campaignType campign type */ public void setCampaignType(CampaignType campaignType) { Log.v(TAG, "setCampaignType"); mCampaignType = campaignType; } /** * This will set up the skip button behaviour setting a name and a delay for it to show up * * @param name name of the string to be shown, any empty string will disable the button * @param delay delay in milliseconds to show the skip button, negative values will disable * the button */ public void setSkip(String name, int delay) { if (TextUtils.isEmpty(name)) { Log.w(TAG, "Skip name set to empty value, this will disable the button"); } else if (delay < 0) { Log.w(TAG, "Skip time set to negative value, this will disable the button"); } mSkipName = name; mSkipDelay = delay; } /** * Sets skip string to be shown in the skip button * * @param skipName skip label * @deprecated Please use setSkip(String, int) instead */ @Deprecated public void setSkipName(String skipName) { // Does nothing } /** * Sets the amount of time that has to be played to be able to skip the video * * @param skipTime skip time * @deprecated Please use setSkip(String, int) instead */ @Deprecated public void setSkipTime(int skipTime) { // Does nothing } // Player actions /** * Starts loading a video VASTModel in the player, it will notify when it's ready with * CachingListener.onVASTPlayerCachingFinish(), so you can start video reproduction. * * @param model model containing the parsed VAST XML */ public void load(VASTModel model) { VASTLog.v(TAG, "load"); // Clean, assign, load setState(PlayerState.Empty); mVastModel = model; mIsDataSourceSet = false; setState(PlayerState.Loading); } /** * Starts video playback if possible */ public void play() { VASTLog.v(TAG, "play"); if (canSetState(PlayerState.Playing)) { setState(PlayerState.Playing); } else if (mPlayerState == PlayerState.Empty) { setState(PlayerState.Ready); } else { VASTLog.e(TAG, "ERROR, player in wrong state: " + mPlayerState.name()); } } /** * Stops video playback */ public void stop() { VASTLog.v(TAG, "stop"); if (canSetState(PlayerState.Loading) && mIsDataSourceSet) { stopTimers(); if(mMediaPlayer != null) { mMediaPlayer.stop(); } setState(PlayerState.Loading); } else { VASTLog.e(TAG, "ERROR, player in wrong state: " + mPlayerState.name()); } } /** * Stops video playback */ public void pause() { VASTLog.v(TAG, "pause"); if (canSetState(PlayerState.Pause) && mIsDataSourceSet) { if(mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.seekTo(0); mMediaPlayer.pause(); } setState(PlayerState.Pause); } else { VASTLog.e(TAG, "ERROR, player in wrong state: " + mPlayerState.name()); } } /** * Destroys current player and clears all loaded data and tracking items */ public void destroy() { VASTLog.v(TAG, "clear"); setState(PlayerState.Empty); } // Private // User Interaction public void onMuteClick() { VASTLog.v(TAG, "onMuteClick"); if (mMediaPlayer != null) { processEvent(mIsVideoMute ? TRACKING_EVENTS_TYPE.unmute : TRACKING_EVENTS_TYPE.mute); mIsVideoMute = !mIsVideoMute; refreshVolume(); } } public void onSkipClick() { VASTLog.v(TAG, "onSkipClick"); processEvent(TRACKING_EVENTS_TYPE.close); stop(); } public void onOpenClick() { VASTLog.v(TAG, "onOpenClick"); stop(); openOffer(); } protected void onPlayClick() { VASTLog.v(TAG, "onPlayClick"); play(); } private void openOffer() { String clickThroughUrl = mVastModel.getVideoClicks().getClickThrough(); VASTLog.d(TAG, "openOffer - clickThrough url: " + clickThroughUrl); // Before we send the app to the click through url, we will process ClickTracking URL's. List<String> urls = mVastModel.getVideoClicks().getClickTracking(); fireUrls(urls); // Navigate to the click through url try { Uri uri = Uri.parse(clickThroughUrl); Intent intent = new Intent(Intent.ACTION_VIEW, uri); ResolveInfo resolvable = getContext().getPackageManager().resolveActivity(intent, PackageManager.GET_INTENT_FILTERS); if (resolvable == null) { VASTLog.e(TAG, "openOffer -clickthrough error occured, uri unresolvable"); return; } else { invokeOnPlayerOpenOffer(); getContext().startActivity(intent); } } catch (NullPointerException e) { VASTLog.e(TAG, e.getMessage(), e); } } // Layout private void createLayout() { VASTLog.v(TAG, "createLayout"); if (mRoot == null) { mRoot = LayoutInflater.from(getContext()).inflate(R.layout.pubnative_player, null); mPlayer = mRoot.findViewById(R.id.player); // Player contained mSurface = (SurfaceView) mPlayer.findViewById(R.id.surface); mSurface.getHolder().addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { Log.v(TAG, "surfaceCreated"); final Surface surface = holder.getSurface(); if ( surface == null ) return; final boolean invalidSurface = ! surface.isValid(); if ( invalidSurface ) return; createMediaPlayer(); mMediaPlayer.setDisplay(holder); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v(TAG, "surfaceChanged"); calculateAspectRatio(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.v(TAG, "surfaceDestroyed"); } }); mMute = (ImageView) mPlayer.findViewById(R.id.mute); mMute.setVisibility(INVISIBLE); mMute.setOnClickListener(this); mCountDown = (CountDownView) mPlayer.findViewById(R.id.count_down); mCountDown.setVisibility(INVISIBLE); mSkip = (TextView) mPlayer.findViewById(R.id.skip); mSkip.setVisibility(INVISIBLE); mSkip.setOnClickListener(this); // Root contained mLoader = mRoot.findViewById(R.id.loader); mLoaderText = (TextView) mRoot.findViewById(R.id.loader_text); mLoaderText.setVisibility(GONE); mPlay = mRoot.findViewById(R.id.play); mPlay.setVisibility(INVISIBLE); mPlay.setOnClickListener(this); mBanner = (ImageView) mRoot.findViewById(R.id.banner); mBanner.setVisibility(INVISIBLE); mOpen = mRoot.findViewById(R.id.open); mOpen.setVisibility(INVISIBLE); mOpen.setOnClickListener(this); addView(mRoot); } } private void showLoader(String message) { mLoader.setVisibility(VISIBLE); mLoaderText.setText(message); mLoaderText.setVisibility(TextUtils.isEmpty(message) ? GONE : VISIBLE); } private void hideLoader() { mLoader.setVisibility(INVISIBLE); } private boolean isBannerReady() { return mBannerBitmap != null; } private void showBanner() { mBanner.setVisibility(VISIBLE); } private void hideBanner() { mBanner.setVisibility(INVISIBLE); } private void showPlay() { mPlay.setVisibility(VISIBLE); } private void hidePlay() { mPlay.setVisibility(INVISIBLE); } private void hideOpen() { mOpen.setVisibility(VISIBLE); } private void showOpen() { mOpen.setVisibility(VISIBLE); } private void hideSurface() { mSurface.setVisibility(INVISIBLE); } private void showSurface() { mSurface.setVisibility(VISIBLE); } private void hidePlayerLayout() { mSkip.setVisibility(INVISIBLE); mMute.setVisibility(INVISIBLE); mCountDown.setVisibility(INVISIBLE); } private void showPlayerLayout() { mSkip.setVisibility(TextUtils.isEmpty(mSkipName) ? INVISIBLE : VISIBLE); mMute.setVisibility(VISIBLE); mCountDown.setVisibility(VISIBLE); } // Media player private void createMediaPlayer() { VASTLog.v(TAG, "createMediaPlayer"); if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } } private void cleanMediaPlayer() { VASTLog.v(TAG, "cleanUpMediaPlayer"); if (mMediaPlayer != null) { turnVolumeOff(); mMediaPlayer.setOnCompletionListener(null); mMediaPlayer.setOnErrorListener(null); mMediaPlayer.setOnPreparedListener(null); mMediaPlayer.setOnVideoSizeChangedListener(null); mMediaPlayer.release(); mMediaPlayer = null; } } public void refreshVolume() { if (mIsVideoMute) { turnVolumeOff(); mMute.setImageResource(R.drawable.pubnative_btn_unmute); } else { turnVolumeOn(); mMute.setImageResource(R.drawable.pubnative_btn_mute); } } public void turnVolumeOff() { mMediaPlayer.setVolume(0.0f, 0.0f); } public void turnVolumeOn() { mMediaPlayer.setVolume(1.0f, 1.0f); } protected void calculateAspectRatio() { VASTLog.v(TAG, "calculateAspectRatio"); if (mVideoWidth == 0 || mVideoHeight == 0) { VASTLog.w(TAG, "calculateAspectRatio - video source width or height is 0, skipping..."); return; } double widthRatio = 1.0 * getWidth() / mVideoWidth; double heightRatio = 1.0 * getHeight() / mVideoHeight; double scale = Math.max(widthRatio, heightRatio); int surfaceWidth = (int) (scale * mVideoWidth); int surfaceHeight = (int) (scale * mVideoHeight); VASTLog.i(TAG, " view size: " + getWidth() + "x" + getHeight()); VASTLog.i(TAG, " video size: " + mVideoWidth + "x" + mVideoHeight); VASTLog.i(TAG, " surface size: " + surfaceWidth + "x" + surfaceHeight); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(surfaceWidth, surfaceHeight); params.addRule(RelativeLayout.CENTER_IN_PARENT); mSurface.setLayoutParams(params); mSurface.getHolder().setFixedSize(surfaceWidth, surfaceHeight); updateLayout(); setAspectRatio((double) mVideoWidth / mVideoHeight); } private void updateLayout() { VASTLog.v(TAG, "updateLayout"); RelativeLayout.LayoutParams muteParams = (RelativeLayout.LayoutParams)mMute.getLayoutParams(); muteParams.addRule(RelativeLayout.ALIGN_TOP, R.id.surface); muteParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.surface); mMute.setLayoutParams(muteParams); RelativeLayout.LayoutParams openParams = (RelativeLayout.LayoutParams)mOpen.getLayoutParams(); openParams.addRule(RelativeLayout.ALIGN_TOP, R.id.surface); openParams.addRule(RelativeLayout.ALIGN_RIGHT, R.id.surface); mOpen.setLayoutParams(openParams); RelativeLayout.LayoutParams countDownParams = (RelativeLayout.LayoutParams)mCountDown.getLayoutParams(); countDownParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.surface); countDownParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.surface); mCountDown.setLayoutParams(countDownParams); RelativeLayout.LayoutParams skipParams = (RelativeLayout.LayoutParams)mSkip.getLayoutParams(); skipParams.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.surface); skipParams.addRule(RelativeLayout.ALIGN_RIGHT, R.id.surface); mSkip.setLayoutParams(skipParams); } private void startCaching() { VASTLog.v(TAG, "startCaching"); try { if(!mIsDataSourceSet) { mIsDataSourceSet = true; String videoURL = mVastModel.getPickedMediaFileURL(); mMediaPlayer.setDataSource(videoURL); } mMediaPlayer.prepareAsync(); } catch (Exception exception) { invokeOnFail(exception); destroy(); } } // Event processing private void processEvent(TRACKING_EVENTS_TYPE eventName) { VASTLog.v(TAG, "processEvent: " + eventName); if (mTrackingEventMap != null) { List<String> urls = mTrackingEventMap.get(eventName); fireUrls(urls); } } private void processImpressions() { VASTLog.v(TAG, "processImpressions"); List<String> impressions = mVastModel.getImpressions(); fireUrls(impressions); } private void processErrorEvent() { VASTLog.v(TAG, "processErrorEvent"); List<String> errorUrls = mVastModel.getErrorUrl(); fireUrls(errorUrls); } private void fireUrls(List<String> urls) { VASTLog.v(TAG, "fireUrls"); if (urls != null) { for (String url : urls) { VASTLog.v(TAG, "\tfiring url:" + url); HttpTools.httpGetURL(url); } } else { VASTLog.d(TAG, "\turl list is null"); } } // Timers private void stopTimers() { VASTLog.v(TAG, "stopTimers"); stopQuartileTimer(); stopLayoutTimer(); stopVideoProgressTimer(); mMainHandler.removeMessages(0); } private void startTimers() { VASTLog.v(TAG, "startTimers"); // Stop previous timers so they don't remain hold stopTimers(); // start timers startQuartileTimer(); startLayoutTimer(); startVideoProgressTimer(); } // Progress timer private void startVideoProgressTimer() { VASTLog.d(TAG, "startVideoProgressTimer"); mProgressTimer = new Timer(); mProgressTracker = new ArrayList<Integer>(); mProgressTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (mProgressTracker.size() > MAX_PROGRESS_TRACKING_POINTS) { int firstPosition = mProgressTracker.get(0); int lastPosition = mProgressTracker.get(mProgressTracker.size() - 1); if (lastPosition > firstPosition) { if (mIsBufferingShown) { mIsBufferingShown = false; mMainHandler.post(new Runnable() { @Override public void run() { hideLoader(); } }); } } else { if (!mIsBufferingShown) { mIsBufferingShown = true; mMainHandler.post(new Runnable() { @Override public void run() { showLoader(TEXT_BUFFERING); } }); } } mProgressTracker.remove(0); } mProgressTracker.add(mMediaPlayer.getCurrentPosition()); } }, 0, TIMER_PROGRESS_INTERVAL); } private void stopVideoProgressTimer() { VASTLog.d(TAG, "stopVideoProgressTimer"); if (mProgressTimer != null) { mProgressTimer.cancel(); mProgressTimer = null; } } // Quartile timer private void startQuartileTimer() { VASTLog.v(TAG, "startQuartileTimer"); mQuartile = 0; mTrackingEventsTimer = new Timer(); mTrackingEventsTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { int percentage = 0; try { // wait for the video to really start if (mMediaPlayer.getCurrentPosition() == 0) { return; } percentage = 100 * mMediaPlayer.getCurrentPosition() / mMediaPlayer.getDuration(); } catch (Exception e) { VASTLog.e(TAG, "QuartileTimer error: " + e.getMessage()); cancel(); return; } if (percentage >= 25 * mQuartile) { if (mQuartile == 0) { VASTLog.i(TAG, "Video at start: (" + percentage + "%)"); processImpressions(); processEvent(TRACKING_EVENTS_TYPE.start); invokeOnPlayerPlaybackStart(); } else if (mQuartile == 1) { VASTLog.i(TAG, "Video at first quartile: (" + percentage + "%)"); processEvent(TRACKING_EVENTS_TYPE.firstQuartile); } else if (mQuartile == 2) { VASTLog.i(TAG, "Video at midpoint: (" + percentage + "%)"); processEvent(TRACKING_EVENTS_TYPE.midpoint); } else if (mQuartile == 3) { VASTLog.i(TAG, "Video at third quartile: (" + percentage + "%)"); processEvent(TRACKING_EVENTS_TYPE.thirdQuartile); stopQuartileTimer(); } mQuartile++; } } }, 0, TIMER_TRACKING_INTERVAL); } private void stopQuartileTimer() { VASTLog.v(TAG, "stopQuartileTimer"); if (mTrackingEventsTimer != null) { mTrackingEventsTimer.cancel(); mTrackingEventsTimer = null; } } // Layout timer private void startLayoutTimer() { VASTLog.v(TAG, "startLayoutTimer"); mLayoutTimer = new Timer(); mLayoutTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (mMediaPlayer == null) { cancel(); return; } // Execute with handler to be sure we execute this on the UIThread mMainHandler.post(new Runnable() { @Override public void run() { try { if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { int currentPosition = mMediaPlayer.getCurrentPosition(); mCountDown.setProgress(currentPosition, mMediaPlayer.getDuration()); if (!TextUtils.isEmpty(mSkipName) && mSkipDelay > currentPosition) { mSkip.setText(mSkipName); mSkip.setVisibility(View.VISIBLE); } } } catch (Exception e) { Log.e(TAG, "Layout timer error: " + e); cancel(); return; } } }); } }, 0, TIMER_LAYOUT_INTERVAL); } private void stopLayoutTimer() { VASTLog.d(TAG, "stopLayoutTimer"); if (mLayoutTimer != null) { mLayoutTimer.cancel(); mLayoutTimer = null; } } // Listener helpers private void invokeOnPlayerOpenOffer() { VASTLog.v(TAG, "invokeOnPlayerClick"); if (mListener != null) { mListener.onVASTPlayerOpenOffer(); } } private void invokeOnPlayerLoadFinish() { VASTLog.v(TAG, "invokeOnPlayerLoadFinish"); if (mListener != null) { mListener.onVASTPlayerLoadFinish(); } } private void invokeOnFail(Exception exception) { VASTLog.v(TAG, "invokeOnFail"); if (mListener != null) { mListener.onVASTPlayerFail(exception); } } private void invokeOnPlayerPlaybackStart() { VASTLog.v(TAG, "invokeOnPlayerPlaybackStart"); if (mListener != null) { mListener.onVASTPlayerPlaybackStart(); } } private void invokeOnPlayerPlaybackFinish() { VASTLog.v(TAG, "invokeOnPlayerPlaybackFinish"); if (mListener != null) { mListener.onVASTPlayerPlaybackFinish(); } } // CALLBACKS // MediaPlayer.OnCompletionListener @Override public void onCompletion(MediaPlayer mediaPlayer) { VASTLog.v(TAG, "onCompletion -- (MediaPlayer callback)"); if (mQuartile > 3) { processEvent(TRACKING_EVENTS_TYPE.complete); invokeOnPlayerPlaybackFinish(); } stop(); } // MediaPlayer.OnErrorListener @Override public boolean onError(MediaPlayer mp, int what, int extra) { VASTLog.v(TAG, "onError -- (MediaPlayer callback)"); processErrorEvent(); String exceptionMessage; switch (what) { case MediaPlayer.MEDIA_ERROR_SERVER_DIED: exceptionMessage = "server died: "; break; case MediaPlayer.MEDIA_ERROR_UNKNOWN: default: exceptionMessage = "unknown: "; } switch (extra) { case MediaPlayer.MEDIA_ERROR_IO: exceptionMessage += "MEDIA_ERROR_IO"; break; case MediaPlayer.MEDIA_ERROR_MALFORMED: exceptionMessage += "MEDIA_ERROR_MALFORMED"; break; case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: exceptionMessage += "MEDIA_ERROR_UNSUPPORTED"; break; case MediaPlayer.MEDIA_ERROR_TIMED_OUT: exceptionMessage += "MEDIA_ERROR_TIMED_OUT"; break; default: exceptionMessage += "low-level system error"; } invokeOnFail(new Exception("VASTPlayer error: " + exceptionMessage)); destroy(); return true; } // MediaPlayer.OnPreparedListener @Override public void onPrepared(MediaPlayer mp) { VASTLog.v(TAG, "onPrepared --(MediaPlayer callback) ....about to play"); setState(PlayerState.Ready); invokeOnPlayerLoadFinish(); } // MediaPlayer.OnVideoSizeChangedListener @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { VASTLog.v(TAG, "onVideoSizeChanged -- " + width + " x " + height); mVideoWidth = width; mVideoHeight = height; } // View.OnClickListener public void onClick(View view) { VASTLog.v(TAG, "onClick -- (View.OnClickListener callback)"); if (mPlay == view) { onPlayClick(); } else if (mOpen == view) { onOpenClick(); } else if (mSkip == view) { onSkipClick(); } else if (mMute == view) { onMuteClick(); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { Log.v(TAG, "onSizeChanged"); super.onSizeChanged(w, h, oldw, oldh); new Handler().post(new Runnable() { @Override public void run() { calculateAspectRatio(); } }); } }
package ru.beykerykt.bullsandcows.implementation; import java.awt.EventQueue; import java.awt.Font; import java.awt.FontFormatException; import java.awt.GraphicsEnvironment; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.SwingConstants; import ru.beykerykt.bullsandcows.base.players.bot.finder.CodeFinder; import ru.beykerykt.bullsandcows.base.players.bot.finder.RandomFinder; import ru.beykerykt.bullsandcows.base.players.bot.finder.bob.BobFinder; import ru.beykerykt.bullsandcows.base.utils.GameUtils; import ru.beykerykt.bullsandcows.implementation.Resources.Localization; public class GUi { // Fonts private GraphicsEnvironment environment; private Font fontBig; private Font fontRegular; private Font fontItalic; // Swing / AWT private JFrame frame; private JTextField usercode; private JTextField pName; private JTextField bName; private JComboBox<String> algorithms; private JButton start; private JLabel botCode; private JButton randomButton; private JLabel attempt; // GameBase private CodeFinder finder; private int guesses = 0; private boolean run = false; private ScheduledFuture<?> sf; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { GUi window = new GUi(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public GUi() { initialize(); } /** * Register custom fonts */ private void registerFonts() { try { fontRegular = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream(Resources.ResourcePaths.REGULAR_FONT_PATH)).deriveFont(14f); environment.registerFont(fontRegular); fontItalic = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream(Resources.ResourcePaths.ITALIC_FONT_PATH)).deriveFont(14f); environment.registerFont(fontItalic); fontBig = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream(Resources.ResourcePaths.REGULAR_FONT_PATH)).deriveFont(60f); environment.registerFont(fontBig); } catch (FontFormatException | IOException e) { e.printStackTrace(); } } /** * Initialize the contents of the frame. */ @SuppressWarnings({ "rawtypes", "unchecked" }) private void initialize() { if (environment == null) { environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); } // Register fonts registerFonts(); // Frame frame = new JFrame(); frame.setTitle(Localization.TITLE_NAME + " [" + Localization.STAGE_VERSION + "]"); try { frame.setIconImage(ImageIO.read(getClass().getResourceAsStream(Resources.ResourcePaths.ICON_PATH))); } catch (IOException e) { e.printStackTrace(); } frame.getContentPane().setFont(fontRegular); frame.getContentPane().setBackground(Resources.Colors.WHITE); frame.setResizable(false); frame.setBounds(100, 100, 550, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); // Start: NOT AVAILABLE IN DEVELOP BRANCH // Player name JLabel playerName = new JLabel(Resources.Localization.PLAYER_NAME.toUpperCase()); playerName.setForeground(Resources.Colors.CYAN); playerName.setFont(fontRegular); playerName.setBounds(10, 11, 190, 20); frame.getContentPane().add(playerName); pName = new JTextField(); pName.setEnabled(false); pName.setEditable(false); pName.setToolTipText(Localization.UNAVAILABLE); pName.setFont(fontItalic); pName.setBounds(10, 42, 190, 20); pName.setColumns(10); pName.setText(Localization.PLAYER_DEFAULT_NAME); frame.getContentPane().add(pName); // Bot name JLabel botName = new JLabel(Resources.Localization.BOT_NAME.toUpperCase()); botName.setForeground(Resources.Colors.CYAN); botName.setFont(fontRegular); botName.setBounds(10, 73, 190, 20); frame.getContentPane().add(botName); bName = new JTextField(); bName.setEnabled(false); bName.setEditable(false); bName.setToolTipText(Localization.UNAVAILABLE); bName.setFont(fontItalic); bName.setBounds(10, 104, 190, 20); bName.setColumns(10); bName.setText(Localization.BOT_DEFAULT_NAME); frame.getContentPane().add(bName); // End: NOT AVAILABLE IN DEVELOP BRANCH // Usercode JLabel yourCode = new JLabel(Localization.YOUR_CODE.toUpperCase()); yourCode.setForeground(Resources.Colors.CYAN); yourCode.setToolTipText(Localization.YOUR_CODE_DESCRPTION); yourCode.setFont(fontRegular); yourCode.setBounds(10, 135, 190, 20); frame.getContentPane().add(yourCode); usercode = new JTextField(); usercode.setToolTipText(Localization.YOUR_CODE_DESCRPTION); usercode.setBounds(10, 166, 190, 20); usercode.setFont(fontItalic); usercode.setColumns(10); frame.getContentPane().add(usercode); // Algorithm's JLabel algorithm = new JLabel(Resources.Localization.Algoritms.ALGORITHM_FOR_SEARCH.toUpperCase()); algorithm.setForeground(Resources.Colors.CYAN); algorithm.setFont(fontRegular); algorithm.setBounds(10, 197, 190, 20); frame.getContentPane().add(algorithm); algorithms = new JComboBox<String>(); algorithms.setBackground(Resources.Colors.WHITE); algorithms.setEditable(false); algorithms.setModel(new DefaultComboBoxModel(new String[] { Resources.Localization.Algoritms.RANDOM_ALGORITHM, Resources.Localization.Algoritms.BOB_ALGORITHM, Resources.Localization.Algoritms.MAGIC_ALGORITHM })); algorithms.setFont(fontItalic); algorithms.setBounds(10, 228, 190, 20); frame.getContentPane().add(algorithms); // Start button start = new JButton(Resources.Localization.START_SEARCHING.toUpperCase()); start.setBackground(Resources.Colors.CYAN); start.setForeground(Resources.Colors.WHITE); start.setFont(fontItalic); start.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (!run) { start(); } else { stop(); } } }); start.setBounds(10, 310, 190, 50); frame.getContentPane().add(start); // Bot code botCode = new JLabel("0000"); botCode.setForeground(Resources.Colors.CYAN); botCode.setHorizontalAlignment(SwingConstants.CENTER); botCode.setFont(fontBig); botCode.setBounds(261, 52, 220, 89); frame.getContentPane().add(botCode); // I think, it's... JLabel ithink = new JLabel(Resources.Localization.I_THINK); ithink.setHorizontalAlignment(SwingConstants.CENTER); ithink.setFont(fontRegular); ithink.setBounds(261, 40, 220, 20); frame.getContentPane().add(ithink); // Attempts attempt = new JLabel(Resources.Localization.ATTEMPT + guesses); attempt.setHorizontalAlignment(SwingConstants.CENTER); attempt.setFont(fontRegular); attempt.setBounds(261, 140, 220, 20); frame.getContentPane().add(attempt); // Get Random Code randomButton = new JButton(Resources.Localization.RANDOM_BUTTON.toUpperCase()); randomButton.setBackground(Resources.Colors.CYAN); randomButton.setForeground(Resources.Colors.WHITE); randomButton.setFont(fontItalic); randomButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (randomButton.isEnabled()) { usercode.setText(GameUtils.generateRandomCode()); } } }); randomButton.setBounds(10, 269, 190, 30); frame.getContentPane().add(randomButton); String[] columnNames = { "Попытка", "Код", "Ответ" }; String[][] data = { { "0", "-", "-", "-" } }; JTable table = new JTable(data, columnNames); table.setEnabled(false); table.setToolTipText(Localization.UNAVAILABLE); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setBounds(241, 186, 280, 174); scrollPane.setEnabled(false); scrollPane.setToolTipText(Localization.UNAVAILABLE); frame.getContentPane().add(scrollPane); } /** * Stop */ public void stop() { // Enable random button randomButton.setEnabled(true); // Enable usercode usercode.setEnabled(true); usercode.setEditable(true); // Enable algorithms list algorithms.setEnabled(true); // Shutdown run = false; sf.cancel(false); GameUtils.shutdownExecutor(true); start.setText(Resources.Localization.START_SEARCHING.toUpperCase()); } /** * Start */ public void start() { // Disable random button randomButton.setEnabled(false); // Disable usercode usercode.setEnabled(false); usercode.setEditable(false); // Disable algorithms list algorithms.setEnabled(false); algorithms.setEditable(false); // Checking try { Integer.valueOf(usercode.getText()); } catch (Exception ex) { // Set null usercode.setText(null); } if (usercode.getText().isEmpty() || usercode.getText().length() > 4) { usercode.setText(GameUtils.generateRandomCode()); // set random code } // Start searching start.setText(Resources.Localization.STOP_SEARCHING.toUpperCase()); if (algorithms.getSelectedItem().equals(Resources.Localization.Algoritms.RANDOM_ALGORITHM)) { finder = new RandomFinder(); } else if (algorithms.getSelectedItem().equals(Resources.Localization.Algoritms.BOB_ALGORITHM)) { finder = new BobFinder(); } else if (algorithms.getSelectedItem().equals(Resources.Localization.Algoritms.MAGIC_ALGORITHM)) { // Fast implementation for Magic algorithm finder = new CodeFinder() { @Override public void reset() { } @Override public void onReceivingResponse(String response) { } @Override public String getGuessCode() { return usercode.getText(); } }; } // Reset fields guesses = 0; finder.reset(); // Start thread GameUtils.shutdownExecutor(false); sf = GameUtils.getExecutorService().scheduleAtFixedRate(new Runnable() { @Override public void run() { String guess = finder.getGuessCode(); botCode.setText(guess); guesses++; attempt.setText(Resources.Localization.ATTEMPT + guesses); String response = getHint(guess); if (response.equals("WON")) { stop(); } } }, 0, 5, TimeUnit.MILLISECONDS); run = true; } public String getHint(String guessFromAnotherPlayer) { int bulls = 0; int cows = 0; if (guessFromAnotherPlayer.length() < GameUtils.CODE_LENGTH) { return bulls + ":" + cows; } for (int i = 0; i < usercode.getText().length(); i++) { if (guessFromAnotherPlayer.charAt(i) == usercode.getText().charAt(i)) { bulls++; } else if (usercode.getText().contains(guessFromAnotherPlayer.charAt(i) + "")) { cows++; } } if (bulls == usercode.getText().length()) { return "WON"; } // System.out.println(cows + " Cows and " + bulls + " Bulls."); return bulls + ":" + cows; } }
package com.jbooktrader.platform.strategy; import com.ib.client.*; import com.jbooktrader.platform.c2.*; import com.jbooktrader.platform.chart.*; import com.jbooktrader.platform.commission.*; import com.jbooktrader.platform.indicator.*; import com.jbooktrader.platform.marketbook.*; import com.jbooktrader.platform.model.*; import static com.jbooktrader.platform.model.Dispatcher.Mode.*; import com.jbooktrader.platform.optimizer.*; import com.jbooktrader.platform.performance.*; import com.jbooktrader.platform.position.*; import com.jbooktrader.platform.report.*; import com.jbooktrader.platform.schedule.*; import com.jbooktrader.platform.trader.*; /** * Base class for all classes that implement trading strategies. */ public abstract class Strategy implements Comparable<Strategy> { private final StrategyParams params; private MarketBook marketBook; private final Report eventReport; private final String name; private Contract contract; private TradingSchedule tradingSchedule; private PositionManager positionManager; private PerformanceManager performanceManager; private StrategyReportManager strategyReportManager; private IndicatorManager indicatorManager; private PerformanceChartData performanceChartData; private boolean isActive; private int position; private long time; private boolean isC2enabled; private String c2SystemId; /** * Framework calls this method when order book changes. */ abstract public void onBookChange(); /** * Framework calls this method to set strategy parameter ranges and values. */ abstract protected void setParams(); protected Strategy(StrategyParams params) { this.params = params; if (params.size() == 0) { setParams(); } name = getClass().getSimpleName(); eventReport = Dispatcher.getReporter(); } public void setMarketBook(MarketBook marketBook) { this.marketBook = marketBook; indicatorManager.setMarketBook(marketBook); } public boolean isActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } public int getPosition() { return position; } protected void setPosition(int position) { this.position = position; } public void closePosition() { position = 0; if (positionManager.getPosition() != 0) { Dispatcher.Mode mode = Dispatcher.getMode(); if (mode == ForwardTest || mode == Trade) { String msg = "End of trading interval. Closing current position."; eventReport.report(getName() + ": " + msg); } } } public void setCollective2() { C2TableModel c2TableModel = new C2TableModel(); C2Value c2Value = c2TableModel.getStrategy(name); isC2enabled = c2Value.getIsEnabled(); c2SystemId = c2Value.getId(); } public StrategyParams getParams() { return params; } protected int getParam(String name) throws JBookTraderException { return params.get(name).getValue(); } protected void addParam(String name, int min, int max, int step, int value) { params.add(name, min, max, step, value); } public PositionManager getPositionManager() { return positionManager; } public PerformanceManager getPerformanceManager() { return performanceManager; } public StrategyReportManager getStrategyReportManager() { return strategyReportManager; } public IndicatorManager getIndicatorManager() { return indicatorManager; } public TradingSchedule getTradingSchedule() { return tradingSchedule; } public void setTime(long time) { this.time = time; } public long getTime() { return time; } protected void addIndicator(Indicator indicator) { indicatorManager.addIndicator(indicator); performanceChartData.addIndicator(indicator); } protected void setStrategy(Contract contract, TradingSchedule tradingSchedule, int multiplier, Commission commission, double bidAskSpread, BarSize barSize) { this.contract = contract; contract.m_multiplier = String.valueOf(multiplier); this.tradingSchedule = tradingSchedule; performanceChartData = new PerformanceChartData(barSize); performanceManager = new PerformanceManager(this, multiplier, commission); positionManager = new PositionManager(this); strategyReportManager = new StrategyReportManager(this); TraderAssistant traderAssistant = Dispatcher.getTrader().getAssistant(); marketBook = traderAssistant.createMarketBook(this); traderAssistant.setBidAskSpread(bidAskSpread); indicatorManager = new IndicatorManager(); } public MarketBook getMarketBook() { return marketBook; } public PerformanceChartData getPerformanceChartData() { return performanceChartData; } public Contract getContract() { return contract; } public String getName() { return name; } public boolean isC2enabled() { return isC2enabled; } public String getC2SystemId() { return c2SystemId; } public void process() { if (isActive() && !marketBook.isEmpty()) { MarketSnapshot marketSnapshot = marketBook.getSnapshot(); long instant = marketSnapshot.getTime(); setTime(instant); indicatorManager.updateIndicators(); if (tradingSchedule.contains(instant)) { if (indicatorManager.hasValidIndicators()) { onBookChange(); } } else { closePosition();// force flat position } positionManager.trade(); performanceManager.updatePositionValue(marketSnapshot.getPrice(), positionManager.getPosition()); Dispatcher.fireModelChanged(ModelListener.Event.StrategyUpdate, this); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" ").append(name).append(" ["); sb.append(contract.m_symbol).append("-"); sb.append(contract.m_secType).append("-"); sb.append(contract.m_exchange).append("]"); return sb.toString(); } public String indicatorsState() { String indicatorsState = ""; for (Indicator indicator : indicatorManager.getIndicators()) { if (!indicatorsState.isEmpty()) { indicatorsState += ", "; } indicatorsState += (int) indicator.getValue(); } return indicatorsState; } // Implementing Comparable interface public int compareTo(Strategy other) { return getName().compareTo(other.getName()); } }
package org.jfree.chart.renderer.xy; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.HashUtilities; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.data.xy.XYDataset; import org.jfree.ui.RectangleEdge; import org.jfree.util.PublicCloneable; /** * Line/Step item renderer for an {@link XYPlot}. This class draws lines * between data points, only allowing horizontal or vertical lines (steps). * The example shown here is generated by the * <code>XYStepRendererDemo1.java</code> program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/XYStepRendererSample.png" * alt="XYStepRendererSample.png" /> */ public class XYStepRenderer extends XYLineAndShapeRenderer implements XYItemRenderer, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -8918141928884796108L; /** * The factor (from 0.0 to 1.0) that determines the position of the * step. * * @since 1.0.10. */ private double stepPoint = 1.0d; /** * Constructs a new renderer with no tooltip or URL generation. */ public XYStepRenderer() { this(null, null); } /** * Constructs a new renderer with the specified tool tip and URL * generators. * * @param toolTipGenerator the item label generator (<code>null</code> * permitted). * @param urlGenerator the URL generator (<code>null</code> permitted). */ public XYStepRenderer(XYToolTipGenerator toolTipGenerator, XYURLGenerator urlGenerator) { super(); setBaseToolTipGenerator(toolTipGenerator); setURLGenerator(urlGenerator); setBaseShapesVisible(false); } /** * Returns the fraction of the domain position between two points on which * the step is drawn. The default is 1.0d, which means the step is drawn * at the domain position of the second`point. If the stepPoint is 0.5d the * step is drawn at half between the two points. * * @return The fraction of the domain position between two points where the * step is drawn. * * @see #setStepPoint(double) * * @since 1.0.10 */ public double getStepPoint() { return this.stepPoint; } /** * Sets the step point and sends a {@link RendererChangeEvent} to all * registered listeners. * * @param stepPoint the step point (in the range 0.0 to 1.0) * * @see #getStepPoint() * * @since 1.0.10 */ public void setStepPoint(double stepPoint) { if (stepPoint < 0.0d || stepPoint > 1.0d) { throw new IllegalArgumentException( "Requires stepPoint in [0.0;1.0]"); } this.stepPoint = stepPoint; fireChangeEvent(); } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the vertical axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // do nothing if item is not visible if (!getItemVisible(series, item)) { return; } PlotOrientation orientation = plot.getOrientation(); Paint seriesPaint = getItemPaint(series, item); Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(seriesPaint); g2.setStroke(seriesStroke); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = (Double.isNaN(y1) ? Double.NaN : rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation)); if (pass == 0 && item > 0) { // get the previous data point... double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = (Double.isNaN(y0) ? Double.NaN : rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation)); if (orientation == PlotOrientation.HORIZONTAL) { if (transY0 == transY1) { // this represents the situation // for drawing a horizontal bar. drawLine(g2, state.workingLine, transY0, transX0, transY1, transX1); } else { //this handles the need to perform a 'step'. // calculate the step point double transXs = transX0 + (getStepPoint() * (transX1 - transX0)); drawLine(g2, state.workingLine, transY0, transX0, transY0, transXs); drawLine(g2, state.workingLine, transY0, transXs, transY1, transXs); drawLine(g2, state.workingLine, transY1, transXs, transY1, transX1); } } else if (orientation == PlotOrientation.VERTICAL) { if (transY0 == transY1) { // this represents the situation // for drawing a horizontal bar. drawLine(g2, state.workingLine, transX0, transY0, transX1, transY1); } else { //this handles the need to perform a 'step'. // calculate the step point double transXs = transX0 + (getStepPoint() * (transX1 - transX0)); drawLine(g2, state.workingLine, transX0, transY0, transXs, transY0); drawLine(g2, state.workingLine, transXs, transY0, transXs, transY1); drawLine(g2, state.workingLine, transXs, transY1, transX1, transY1); } } // submit this data item as a candidate for the crosshair point int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, null, dataset, series, item, transX1, transY1); } } if (pass == 1) { // draw the item label if there is one... if (isItemLabelVisible(series, item)) { double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); } } } /** * A utility method that draws a line but only if none of the coordinates * are NaN values. * * @param g2 the graphics target. * @param line the line object. * @param x0 the x-coordinate for the starting point of the line. * @param y0 the y-coordinate for the starting point of the line. * @param x1 the x-coordinate for the ending point of the line. * @param y1 the y-coordinate for the ending point of the line. */ private void drawLine(Graphics2D g2, Line2D line, double x0, double y0, double x1, double y1) { if (Double.isNaN(x0) || Double.isNaN(x1) || Double.isNaN(y0) || Double.isNaN(y1)) { return; } line.setLine(x0, y0, x1, y1); g2.draw(line); } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYLineAndShapeRenderer)) { return false; } XYStepRenderer that = (XYStepRenderer) obj; if (this.stepPoint != that.stepPoint) { return false; } return super.equals(obj); } /** * Returns a hash code for this instance. * * @return A hash code. */ public int hashCode() { return HashUtilities.hashCode(super.hashCode(), this.stepPoint); } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package btl_PI; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Image; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.ImageIcon; import javax.swing.Timer; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import java.util.Random; import java.awt.Color; import javax.swing.JToggleButton; public class PIKaChu extends JFrame { public JButton tieptuc; public int A[] = new int [72]; public JButton btning[] = new JButton[72]; public JPanel contentPane ; public Timer time; public int flag =0; public int bodem; public int map=0; public int lick1 ,click2; public JButton b1,b2; public Border slBorder = new LineBorder(Color.red , 3); public static int gamemap =0; public JMenuItem mntmNewGame = new JMenuItem("new Game"); public int newgame =0; public long score =0; public JLabel scorelabel = new JLabel("Score = "+score); public JLabel timelabel = new JLabel("Time = "+bodem); public JLabel maplabel = new JLabel("Map"+score); Random ran = new Random(); public JPanel panel = new JPanel(); /* main * */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { PIKaChu frame = new PIKaChu(); frame.setVisible(true); }catch(Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public PIKaChu() { setResizable(true); setTitle("PiKaChu"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //dfklgdlkgkdldk }
package io.druid.query; import com.google.common.util.concurrent.ListenableFuture; /** * This interface is in a very early stage and should not be considered stable. * * The purpose of the QueryWatcher is to give overall visibility into queries running * or pending at the QueryRunner level. This is currently used to cancel all the * parts of a pending query, but may be expanded in the future to offer more direct * visibility into query execution and resource usage. * * QueryRunners executing any computation asynchronously must register their queries * with the QueryWatcher. * */ public interface QueryWatcher { /** * QueryRunners must use this method to register any pending queries. * * The given future may have cancel(true) called at any time, if cancellation of this query has been requested. * * @param query a query, which may be a subset of a larger query, as long as the underlying queryId is unchanged * @param future the future holding the execution status of the query */ public void registerQuery(Query query, ListenableFuture future); }
package com.grandmaapp.activities; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import com.example.grandmaapp.R; import com.grandmaapp.services.WishesService; public class GrandmaActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grandma); //startWishesService(); adjustGUI(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.grandma, menu); return true; } public void zeigeEinstellungen(View view) { } private void adjustGUI() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels / 2; int width = displaymetrics.widthPixels / 3; ImageView grandmaImgV = (ImageView) findViewById(R.id.grandmaImgView); grandmaImgV.getLayoutParams().height = height; grandmaImgV.setImageResource(R.drawable.grandma_zufrieden); Button settingsBtn = (Button) findViewById(R.id.einstellungenBtn); Button supplyBtn = (Button) findViewById(R.id.vorraeteBtn); Button testBtn = (Button) findViewById(R.id.testBtn); settingsBtn.setBackgroundResource(R.drawable.settings_selector); supplyBtn.setBackgroundResource(R.drawable.supply_selector); testBtn.setBackgroundResource(R.drawable.test_selector); settingsBtn.getLayoutParams().width = (width - (width / 10)); supplyBtn.getLayoutParams().width = (width - (width / 10)); testBtn.getLayoutParams().width = (width - (width / 10)); LinearLayout linLay = (LinearLayout) findViewById(R.id.tasksLinLay); Button txt1 = new Button(this); txt1.setText("hallo hallo"); txt1.setBackgroundResource(R.drawable.button_selector); txt1.setLayoutParams((new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))); Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Blippo.ttf"); txt1.setTypeface(font); txt1.setTextSize(30); linLay.addView(txt1); Button txt2 = new Button(this); txt2.setText("hallo hallo"); txt2.setBackgroundResource(R.drawable.button_selector); txt2.setLayoutParams((new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))); linLay.addView(txt2); Button txt3 = new Button(this); txt3.setText("hallo hallo"); txt3.setBackgroundResource(R.drawable.button_selector); txt3.setLayoutParams((new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))); linLay.addView(txt3); Button txt4 = new Button(this); txt4.setText("hallo hallo"); txt4.setBackgroundResource(R.drawable.button_selector); txt4.setLayoutParams((new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT))); linLay.addView(txt4); } private void startWishesService() { // Sekundentakt in dem der Service gestartet wird. int refreshInS = 60; Calendar cal = Calendar.getInstance(); Intent intent = new Intent(this, WishesService.class); PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), refreshInS * 1000, pintent); } @Override protected void onDestroy() { // save current state to shared preferences // time, storage, wishes ArrayList<String> valuesToSave = new ArrayList<String>(); String currentDateTimeString = DateFormat.getDateTimeInstance().format( new Date()); valuesToSave.add(currentDateTimeString); super.onDestroy(); } }
package pl.makenika.splot; import android.content.Context; import android.content.res.Resources; import android.util.Log; import android.util.Pair; import org.keplerproject.luajava.JavaFunction; import org.keplerproject.luajava.LuaException; import org.keplerproject.luajava.LuaState; import org.keplerproject.luajava.LuaStateFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class SplotEngine { private static final String TAG = "Splot"; private Context mContext; private LuaState mLuaState; public SplotEngine(Context context) { mContext = context; mLuaState = newState(context); } public Pair<Boolean, String> loadLuaModule(String luaModuleName) throws IOException { luaModuleName = luaModuleName.replaceAll("\\.", "/"); final InputStream is = mContext.getAssets().open("splot_lua/" + luaModuleName + ".lua"); return loadInputStream(is); } public Pair<Boolean, String> loadInputStream(InputStream luaFileInputStream) throws IOException { final String code = readWholeString(luaFileInputStream); final int ret = mLuaState.LdoString(code); if (ret == 1) { final String err = mLuaState.toString(-1); return new Pair<Boolean, String>(Boolean.FALSE, err); } return new Pair<Boolean, String>(Boolean.TRUE, ""); } private static class LuaPrintFunction extends JavaFunction { private LuaPrintFunction(LuaState L) { super(L); } @Override public int execute() throws LuaException { final StringBuilder builder = new StringBuilder(""); for (int i = 2, max = L.getTop(); i <= max; i++) { final String s; final int type = L.type(i); if (type == LuaState.LUA_TUSERDATA) { Object obj = L.toJavaObject(i); if (obj != null) { s = obj.toString(); } else { s = L.toString(i); } } else if (type == LuaState.LUA_TBOOLEAN) { s = L.toBoolean(i) ? "true" : "false"; } else { s = L.toString(i); } builder.append(s); if (i < max) { builder.append("\t"); } } Log.d("Splot", builder.toString()); return 0; } } private static class AssetLoaderFunction extends JavaFunction { private Context mContext; private AssetLoaderFunction(LuaState L, Context context) { super(L); mContext = context; } @Override public int execute() throws LuaException { final Resources resources = mContext.getResources(); final String originalName = L.toString(-1); final String assetName = originalName.replaceAll("\\.", "/"); final String rawName = "splot_lua_" + originalName.replaceAll("\\.", "_"); InputStream is; try { is = mContext.getAssets().open("splot_lua/" + assetName + ".lua"); } catch (IOException e) { is = null; } if (is == null) { try { final int rawId = R.raw.class.getField(rawName).getInt(null); is = resources.openRawResource(rawId); } catch (Exception e) { is = null; } } if (is != null) { try { byte[] bytes = readAllBytes(is); L.LloadBuffer(bytes, rawName); return 1; } catch (IOException e) { e.printStackTrace(); } } L.pushString("\nno file '" + rawName + "' in 'lua' directory"); return 1; } } private static LuaState newState(Context context) { LuaState L = LuaStateFactory.newLuaState(); L.openLibs(); L.getGlobal("package"); L.getField(-1, "loaders"); int nLoaders = L.objLen(-1); // Move the default loaders up, since we want our loader to be the first on the list. for (int i = nLoaders; i >= 1; i L.rawGetI(-1, i); L.rawSetI(-2, i + 1); } try { new LuaPrintFunction(L).register("print"); } catch (LuaException e) { throw new RuntimeException("Could not register 'print' function: " + e.getLocalizedMessage()); } try { L.pushJavaFunction(new AssetLoaderFunction(L, context)); // package loaders loader L.rawSetI(-2, 1); // package loaders L.setTop(0); } catch (LuaException e) { throw new RuntimeException("Could not set the asset loader function: " + e.getLocalizedMessage()); } return L; } private static ByteArrayOutputStream readAll(InputStream inputStream) throws IOException { final int N = 4096; final ByteArrayOutputStream output = new ByteArrayOutputStream(N); final byte[] buffer = new byte[N]; while (true) { final int n = inputStream.read(buffer); if (n >= 0) { output.write(buffer, 0, n); } else { break; } } return output; } private static byte[] readAllBytes(InputStream inputStream) throws IOException { return readAll(inputStream).toByteArray(); } private static String readWholeString(InputStream inputStream) throws IOException { return readAll(inputStream).toString("UTF-8"); } }
package io.crate.planner.symbol; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.spatial4j.core.shape.Shape; import io.crate.operation.Input; import io.crate.types.*; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.BytesRefs; import java.io.IOException; import java.util.*; public class Literal<ReturnType> extends DataTypeSymbol implements Input<ReturnType>, Comparable<Literal> { protected Object value; protected DataType type; public final static Literal<Void> NULL = new Literal<Void>(DataTypes.NULL, null); public final static Literal<BytesRef> EMPTY_STRING = new Literal<BytesRef>(DataTypes.STRING, new BytesRef()); private final static Literal<Boolean> BOOLEAN_TRUE = new Literal<>(DataTypes.BOOLEAN, true); private final static Literal<Boolean> BOOLEAN_FALSE = new Literal<>(DataTypes.BOOLEAN, false); public static final SymbolFactory<Literal> FACTORY = new SymbolFactory<Literal>() { @Override public Literal newInstance() { return new Literal(); } }; /** * guesses the type from the parameters value and creates a new Literal */ public static Literal<?> fromParameter(Parameter parameter) { DataType<?> dataType = DataTypes.guessType(parameter.value(), true); if (dataType.equals(DataTypes.STRING)) { // force conversion to bytesRef return new Literal<>(dataType, dataType.value(parameter.value())); } // all other types are okay as is. return new Literal<>(dataType, parameter.value()); } public static Literal implodeCollection(DataType itemType, Set<Literal> literals) { ImmutableSet.Builder<Object> builder = ImmutableSet.builder(); for (Literal literal : literals) { assert literal.valueType() == itemType : String.format("Literal type: %s does not match item type: %s", literal.valueType(), itemType); builder.add(literal.value()); } return new Literal<>(new SetType(itemType), builder.build()); } public static Literal implodeCollection(DataType itemType, List<Literal> literals) { Object[] values = new Object[literals.size()]; for (int i = 0; i<literals.size(); i++) { assert literals.get(i).valueType() == itemType : String.format("Literal type: %s does not match item type: %s", literals.get(i).valueType(), itemType); values[i] = literals.get(i).value(); } return new Literal<>(new ArrayType(itemType), values); } public static Collection<Literal> explodeCollection(Literal collectionLiteral) { Preconditions.checkArgument(DataTypes.isCollectionType(collectionLiteral.valueType())); Collection values = (Collection) collectionLiteral.value(); List<Literal> literals = new ArrayList<>(values.size()); for (Object value : values) { literals.add(new Literal<>( ((CollectionType)collectionLiteral.valueType()).innerType(), value )); } return literals; } protected Literal() { } protected Literal(DataType type, ReturnType value) { assert typeMatchesValue(type, value) : String.format("value %s is not of type %s", value, type.getName()); this.type = type; this.value = value; } private static <ReturnType> boolean typeMatchesValue(DataType type, ReturnType value) { if (value == null) { return true; } if (type.equals(DataTypes.STRING) && (value instanceof BytesRef || value instanceof String)) { return true; } if (type instanceof ArrayType) { DataType innerType = ((ArrayType) type).innerType(); if (innerType.equals(DataTypes.STRING)) { for (Object o : ((Object[]) value)) { if (o != null && !(o instanceof String || o instanceof BytesRef)) { return false; } } return true; } else { return Arrays.equals(((Object[]) value), (Object[]) type.value(value)); } } // types like GeoPoint are represented as arrays if (value.getClass().isArray() && Arrays.equals(((Object[]) value), ((Object[]) type.value(value)))) { return true; } return type.value(value).equals(value); } @Override @SuppressWarnings("unchecked") public int compareTo(Literal o) { return type.compareValueTo(value, o.value); } @Override @SuppressWarnings("unchecked") public ReturnType value() { return (ReturnType)value; } @Override public DataType valueType() { return type; } @Override public SymbolType symbolType() { return SymbolType.LITERAL; } @Override public <C, R> R accept(SymbolVisitor<C, R> visitor, C context) { return visitor.visitLiteral(this, context); } @Override public int hashCode() { return Objects.hashCode(value()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Literal literal = (Literal) obj; if (valueType().equals(literal.valueType())) { return Objects.equals(value(), literal.value()); } return false; } @Override public String toString() { return "Literal{" + "value=" + BytesRefs.toString(value) + ", type=" + type + '}'; } @Override @SuppressWarnings("unchecked") public void readFrom(StreamInput in) throws IOException { type = DataTypes.fromStream(in); value = type.streamer().readValueFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { DataTypes.toStream(type, out); type.streamer().writeValueTo(out, value); } public static Literal<Map<String, Object>> newLiteral(Map<String, Object> value) { return new Literal<>(DataTypes.OBJECT, value); } public static Literal<Object[]> newLiteral(Object[] value, DataType dataType) { return new Literal<>(dataType, value); } public static Literal<Long> newLiteral(Long value) { return new Literal<>(DataTypes.LONG, value); } public static Literal<Object> newLiteral(DataType type, Object value) { return new Literal<>(type, value); } public static Literal<Integer> newLiteral(Integer value) { return new Literal<>(DataTypes.INTEGER, value); } public static Literal<BytesRef> newLiteral(String value) { if (value == null) { return new Literal<>(DataTypes.STRING, null); } return new Literal<>(DataTypes.STRING, new BytesRef(value)); } public static Literal<BytesRef> newLiteral(BytesRef value) { return new Literal<>(DataTypes.STRING, value); } public static Literal<Boolean> newLiteral(Boolean value) { if (value == null) { return new Literal<>(DataTypes.BOOLEAN, null); } return value ? BOOLEAN_TRUE : BOOLEAN_FALSE; } public static Literal<Double> newLiteral(Double value) { return new Literal<>(DataTypes.DOUBLE, value); } public static Literal<Float> newLiteral(Float value) { return new Literal<>(DataTypes.FLOAT, value); } public static Literal<Shape> newGeoShape(String value) { return new Literal<>(DataTypes.GEO_SHAPE, DataTypes.GEO_SHAPE.value(value)); } public static Literal toLiteral(Symbol symbol, DataType type) throws IllegalArgumentException { switch (symbol.symbolType()) { case PARAMETER: return Literal.newLiteral(type, type.value(((Parameter) symbol).value())); case LITERAL: Literal literal = (Literal)symbol; if (literal.valueType().equals(type)) { return literal; } return Literal.newLiteral(type, type.value(literal.value())); } throw new IllegalArgumentException("expected a parameter or literal symbol"); } public static Literal toLiteral(Symbol s) { switch (s.symbolType()) { case PARAMETER: return Literal.fromParameter((Parameter) s); case LITERAL: return (Literal) s; default: throw new IllegalArgumentException("expected a parameter or literal symbol"); } } }
/* * $Log: RestUriComparator.java,v $ * Revision 1.2 2011-05-23 15:32:59 L190409 * first bugfixes * * Revision 1.1 2011/05/19 15:11:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * first version of Rest-provider support * */ package nl.nn.adapterframework.http; import java.util.Comparator; import org.apache.commons.lang.StringUtils; /** * @author Gerrit van Brakel * @since * @version Id */ public class RestUriComparator implements Comparator { public int compare(Object o1, Object o2) { String uri1=(String) o1; String uri2=(String) o2; if (StringUtils.isEmpty(uri1)) { return StringUtils.isEmpty(uri2)?0:1; } int result=uri2.length()-uri1.length(); if (result==0) { result=uri1.compareTo(uri2); } return result; } }
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.MeasureType; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Protocol; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.characterization.CharacterizationTypeBean; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; import org.hibernate.Hibernate; import org.hibernate.SQLQuery; import org.hibernate.collection.PersistentSet; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.116 2007-06-26 22:04:14 pansu Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CaNanoLabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CaNanoLabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CaNanoLabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { Map<String, List<String>> allUnits = getAllMeasureUnits(); List<StorageElement> storageElements = getAllStorageElements(); List<String> quantityUnits = (allUnits.get("Quantity") == null) ? new ArrayList<String>() : allUnits.get("Quantity"); List<String> concentrationUnits = (allUnits.get("Concentration") == null) ? new ArrayList<String>() : allUnits.get("Concentration"); List<String> volumeUnits = (allUnits.get("Volume") == null) ? new ArrayList<String>() : allUnits.get("Volume"); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); List<String> shelves = new ArrayList<String>(); List<String> boxes = new ArrayList<String>(); for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room") && !rooms.contains(storageElement.getLocation())) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer") && !freezers.contains(storageElement.getLocation())) { freezers.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Shelf") && !shelves.contains(storageElement.getLocation())) { shelves.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Box") && !boxes.contains(storageElement.getLocation())) { boxes.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers, shelves, boxes); return containerInfo; } public List<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public List<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public Map<String, List<String>> getAllMeasureUnits() throws Exception { Map<String, List<String>> unitMap = new HashMap<String, List<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit unit order by unit.name"; List results = ida.search(hqlString); List<String> units = null; for (Object obj : results) { MeasureUnit unit = (MeasureUnit) obj; String type = unit.getType(); if (unitMap.get(type) != null) { units = unitMap.get(type); } else { units = new ArrayList<String>(); unitMap.put(type, units); } units.add(unit.getName()); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return unitMap; } public List<String> getAllMeasureTypes() throws Exception { List<String> types = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureType type order by type.name"; List results = ida.search(hqlString); for (Object obj : results) { MeasureType type = (MeasureType) obj; types.add(type.getName()); } } catch (Exception e) { logger.error("Error in retrieving all measure types", e); throw new RuntimeException("Error in retrieving all measure types."); } finally { ida.close(); } return types; } private List<StorageElement> getAllStorageElements() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer', 'Shelf', 'Box') and location!='Other'"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CaNanoLabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CaNanoLabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { // TODO: temp for debuging use. remove later e.printStackTrace(); logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public List<String> getAllSampleSources() throws Exception { List<String> sampleSources = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CaNanoLabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); try { ida.open(); // String hqlString = "select particle.type, particle.name from // Nanoparticle particle"; String hqlString = "select particle.type, particle.name from Nanoparticle particle where size(particle.characterizationCollection) = 0"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { // check if the particle already has visibility group // assigned, if yes, do NOT add to the list List<String> groups = userService.getAccessibleGroups( particleName, CaNanoLabConstants.CSM_READ_ROLE); if (groups.size() == 0) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CaNanoLabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } public String[] getAllDendrimerCores() { String[] cores = new String[] { "Diamine", "Ethyline" }; return cores; } public String[] getAllDendrimerSurfaceGroupNames() throws Exception { SortedSet<String> names = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct surfaceGroup.name from SurfaceGroup surfaceGroup where surfaceGroup.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { names.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Surface Group name."); throw new RuntimeException( "Problem to retrieve all Surface Group name. "); } finally { ida.close(); } names.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_SURFACE_GROUP_NAMES)); return (String[]) names.toArray(new String[0]); } public String[] getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_BRANCHES)); return (String[]) branches.toArray(new String[0]); } public String[] getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_GENERATIONS)); return (String[]) generations.toArray(new String[0]); } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public String[] getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer where polymer.initiator is not null "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_POLYMER_INITIATORS)); return (String[]) initiators.toArray(new String[0]); } public List<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String classification = CaNanoLabConstants.PARTICLE_CLASSIFICATION_MAP .get(particleType); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, List<String>> getCharacterizationTypeCharacterizations() throws Exception { Map<String, List<String>> charTypeChars = new HashMap<String, List<String>>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); List<String> chars = null; String query = "select distinct a.category, a.name from def_characterization_category a " + "where a.name not in (select distinct b.category from def_characterization_category b) " + "order by a.category, a.name"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("NAME", Hibernate.STRING); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); String name = objarr[1].toString(); if (charTypeChars.get(type) != null) { chars = (List<String>) charTypeChars.get(type); } else { chars = new ArrayList<String>(); charTypeChars.put(type, chars); } chars.add(name); } } catch (Exception e) { logger .error("Problem to retrieve all characterization type characterizations. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion type characterizations. "); } finally { hda.close(); } return charTypeChars; } public List<LabelValueBean> getAllInstrumentTypeAbbrs() throws Exception { List<LabelValueBean> instrumentTypeAbbrs = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, instrumentType.abbreviation from InstrumentType instrumentType where instrumentType.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) { Object[] objs = (Object[]) obj; String label = ""; if (objs[1] != null) { label = (String) objs[0] + "(" + objs[1] + ")"; } else { label = (String) objs[0]; } instrumentTypeAbbrs.add(new LabelValueBean(label, (String) objs[0])); } } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } instrumentTypeAbbrs.add(new LabelValueBean(CaNanoLabConstants.OTHER, CaNanoLabConstants.OTHER)); return instrumentTypeAbbrs; } public Map<String, SortedSet<String>> getAllInstrumentManufacturers() throws Exception { Map<String, SortedSet<String>> instrumentManufacturers = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; List results = ida.search(hqlString); SortedSet<String> manufacturers = null; for (Object obj : results) { String instrumentType = ((Object[]) obj)[0].toString(); String manufacturer = ((Object[]) obj)[1].toString(); if (instrumentManufacturers.get(instrumentType) != null) { manufacturers = (SortedSet<String>) instrumentManufacturers .get(instrumentType); } else { manufacturers = new TreeSet<String>(); instrumentManufacturers.put(instrumentType, manufacturers); } manufacturers.add(manufacturer); } List allResult = ida .search("select manufacturer.name from Manufacturer manufacturer where manufacturer.name is not null"); SortedSet<String> allManufacturers = null; allManufacturers = new TreeSet<String>(); for (Object obj : allResult) { String name = (String) obj; allManufacturers.add(name); } instrumentManufacturers.put(CaNanoLabConstants.OTHER, allManufacturers); } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument types " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument types."); } finally { ida.close(); } return instrumentManufacturers; } public String[] getAllMorphologyTypes() throws Exception { SortedSet<String> morphologyTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct morphology.type from Morphology morphology"; List results = ida.search(hqlString); for (Object obj : results) { morphologyTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all morphology types."); throw new RuntimeException( "Problem to retrieve all morphology types."); } finally { ida.close(); } morphologyTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_MORPHOLOGY_TYPES)); return (String[]) morphologyTypes.toArray(new String[0]); } public String[] getAllShapeTypes() throws Exception { SortedSet<String> shapeTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct shape.type from Shape shape where shape.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { shapeTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all shape types."); throw new RuntimeException("Problem to retrieve all shape types."); } finally { ida.close(); } shapeTypes .addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_SHAPE_TYPES)); return (String[]) shapeTypes.toArray(new String[0]); } public Map<ProtocolBean, List<ProtocolFileBean>> getAllProtocolNameVersionByType( String type) throws Exception { Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = new HashMap<ProtocolBean, List<ProtocolFileBean>>(); Map<Protocol, ProtocolBean> keyMap = new HashMap<Protocol, ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocolFile, protocolFile.protocol from ProtocolFile protocolFile" + " where protocolFile.protocol.type = '" + type + "'"; List results = ida.search(hqlString); for (Object obj : results) { Object[] array = (Object[]) obj; Object key = null; Object value = null; for (int i = 0; i < array.length; i++) { if (array[i] instanceof Protocol) { key = array[i]; } else if (array[i] instanceof ProtocolFile) { value = array[i]; } } if (keyMap.containsKey((Protocol) key)) { ProtocolBean pb = keyMap.get((Protocol) key); List<ProtocolFileBean> localList = nameVersions.get(pb); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); } else { List<ProtocolFileBean> localList = new ArrayList<ProtocolFileBean>(); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); ProtocolBean protocolBean = new ProtocolBean(); Protocol protocol = (Protocol) key; protocolBean.setId(protocol.getId().toString()); protocolBean.setName(protocol.getName()); protocolBean.setType(protocol.getType()); nameVersions.put(protocolBean, localList); keyMap.put((Protocol) key, protocolBean); } } } catch (Exception e) { logger .error("Problem to retrieve all protocol names and their versions by type " + type); throw new RuntimeException( "Problem to retrieve all protocol names and their versions by type " + type); } finally { ida.close(); } return nameVersions; } public SortedSet<String> getAllProtocolTypes() throws Exception { SortedSet<String> protocolTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct protocol.type from Protocol protocol where protocol.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol types."); throw new RuntimeException( "Problem to retrieve all protocol types."); } finally { ida.close(); } return protocolTypes; } public SortedSet<ProtocolBean> getAllProtocols(UserBean user) throws Exception { SortedSet<ProtocolBean> protocolBeans = new TreeSet<ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Protocol as protocol left join fetch protocol.protocolFileCollection"; List results = ida.search(hqlString); for (Object obj : results) { Protocol p = (Protocol) obj; ProtocolBean pb = new ProtocolBean(); pb.setId(p.getId().toString()); pb.setName(p.getName()); pb.setType(p.getType()); PersistentSet set = (PersistentSet) p .getProtocolFileCollection(); // HashSet hashSet = set. if (!set.isEmpty()) { List<ProtocolFileBean> list = new ArrayList<ProtocolFileBean>(); for (Iterator it = set.iterator(); it.hasNext();) { ProtocolFile pf = (ProtocolFile) it.next(); ProtocolFileBean pfb = new ProtocolFileBean(); pfb.setId(pf.getId().toString()); pfb.setVersion(pf.getVersion()); list.add(pfb); } pb.setFileBeanList(filterProtocols(list, user)); } if (!pb.getFileBeanList().isEmpty()) protocolBeans.add(pb); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names and types."); throw new RuntimeException( "Problem to retrieve all protocol names and types."); } finally { ida.close(); } return protocolBeans; } private List<ProtocolFileBean> filterProtocols( List<ProtocolFileBean> protocolFiles, UserBean user) throws Exception { UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<LabFileBean> tempList = new ArrayList<LabFileBean>(); for (ProtocolFileBean pfb : protocolFiles) { tempList.add((LabFileBean) pfb); } List<LabFileBean> filteredProtocols = userService.getFilteredFiles( user, tempList); protocolFiles.clear(); if (filteredProtocols == null || filteredProtocols.isEmpty()) return protocolFiles; for (LabFileBean lfb : filteredProtocols) { protocolFiles.add((ProtocolFileBean) lfb); } return protocolFiles; } public String[] getAllStressorTypes() { String[] stressorTypes = new String[] { "Thermal", "PH", "Freeze thaw", "Photo", "Centrifugation", "Lyophilization", "Chemical", "Other" }; return stressorTypes; } public String[] getAllAreaMeasureUnits() { String[] areaUnit = new String[] { "sq nm" }; return areaUnit; } public String[] getAllChargeMeasureUnits() { String[] chargeUnit = new String[] { "a.u", "aC", "Ah", "C", "esu", "Fr", "statC" }; return chargeUnit; } public String[] getAllDensityMeasureUnits() { String[] densityUnits = new String[] { "kg/L" }; return densityUnits; } public String[] getAllControlTypes() { String[] controlTypes = new String[] { " ", "Positive", "Negative" }; return controlTypes; } public String[] getAllConditionTypes() { String[] conditionTypes = new String[] { "Particle Concentration", "Temperature", "Time" }; return conditionTypes; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Therapeutic", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public Map<String, String[]> getAllAgentTargetTypes() { Map<String, String[]> agentTargetTypes = new HashMap<String, String[]>(); String[] targetTypes = new String[] { "Receptor", "Antigen", "Other" }; String[] targetTypes1 = new String[] { "Receptor", "Other" }; String[] targetTypes2 = new String[] { "Other" }; agentTargetTypes.put("Small Molecule", targetTypes2); agentTargetTypes.put("Peptide", targetTypes1); agentTargetTypes.put("Antibody", targetTypes); agentTargetTypes.put("DNA", targetTypes1); agentTargetTypes.put("Probe", targetTypes1); agentTargetTypes.put("Other", targetTypes2); agentTargetTypes.put("Image Contrast Agent", targetTypes2); return agentTargetTypes; } public String[] getAllTimeUnits() { String[] timeUnits = new String[] { "hours", "days", "months" }; return timeUnits; } public String[] getAllTemperatureUnits() { String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; return temperatureUnits; } public String[] getAllConcentrationUnits() { String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul" }; return concentrationUnits; } public Map<String, String[]> getAllConditionUnits() { Map<String, String[]> conditionTypeUnits = new HashMap<String, String[]>(); String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul", }; String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; String[] timeUnits = new String[] { "hours", "days", "months" }; conditionTypeUnits.put("Particle Concentration", concentrationUnits); conditionTypeUnits.put("Time", timeUnits); conditionTypeUnits.put("Temperature", temperatureUnits); return conditionTypeUnits; } public String[] getAllCellLines() throws Exception { SortedSet<String> cellLines = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct cellViability.cellLine, caspase.cellLine from CellViability cellViability, Caspase3Activation caspase"; List results = ida.search(hqlString); for (Object obj : results) { // cellLines.add((String) obj); Object[] objects = (Object[]) obj; for (Object object : objects) { if (object != null) { cellLines.add((String) object); } } } } catch (Exception e) { logger.error("Problem to retrieve all Cell lines."); throw new RuntimeException("Problem to retrieve all Cell lines."); } finally { ida.close(); } cellLines.addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_CELLLINES)); return (String[]) cellLines.toArray(new String[0]); } public String[] getAllActivationMethods() { String[] activationMethods = new String[] { "NMR", "MRI", "Radiation", "Ultrasound", "Ultraviolet Light" }; return activationMethods; } public List<LabelValueBean> getAllSpecies() throws Exception { List<LabelValueBean> species = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); species.add(new LabelValueBean("", "")); try { for (int i = 0; i < CaNanoLabConstants.SPECIES_COMMON.length; i++) { String specie = CaNanoLabConstants.SPECIES_COMMON[i]; species.add(new LabelValueBean(specie, specie)); } } catch (Exception e) { logger.error("Problem to retrieve all species. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return species; } public String[] getAllReportTypes() { String[] allReportTypes = new String[] { CaNanoLabConstants.REPORT, CaNanoLabConstants.ASSOCIATED_FILE }; return allReportTypes; } /** * Get other particles from the given particle source * * @param particleSource * @param particleName * @param user * @return * @throws Exception */ public SortedSet<String> getOtherParticles(String particleSource, String particleName, UserBean user) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); SortedSet<String> otherParticleNames = new TreeSet<String>(); try { ida.open(); String hqlString = "select particle.name from Nanoparticle particle where particle.source.organizationName='" + particleSource + "' and particle.name !='" + particleName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String otherParticleName = (String) obj; // check if user can see the particle boolean status = userService.checkReadPermission(user, otherParticleName); if (status) { otherParticleNames.add(otherParticleName); } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return otherParticleNames; } public List<InstrumentBean> getAllInstruments() throws Exception { List<InstrumentBean> instruments = new ArrayList<InstrumentBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Instrument instrument where instrument.type is not null and instrument.manufacturer is not null order by instrument.type"; List results = ida.search(hqlString); for (Object obj : results) { Instrument instrument = (Instrument) obj; instruments.add(new InstrumentBean(instrument)); } } catch (Exception e) { logger.error("Problem to retrieve all instruments. " + e); throw new RuntimeException("Problem to retrieve all intruments. "); } finally { ida.close(); } return instruments; } public List<String> getAllDerivedDataFileTypes() throws Exception { List<String> fileTypes = new ArrayList<String>(); // TODO query from database fileTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DERIVED_DATA_FILE_TYPES)); return fileTypes; } public Map<String, List<String>> getAllDerivedDataCategories() throws Exception { Map<String, List<String>> categoryMap = new HashMap<String, List<String>>(); // TODO query from database List<String> categories = new ArrayList<String>(); categories.add("Volume Distribution"); categories.add("Intensity Distribution"); categories.add("Number Distribution"); categoryMap.put("Size", categories); return categoryMap; } public List<String> getAllFunctionTypes() throws Exception { List<String> types = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select funcType.name from FunctionType funcType order by funcType.name"; List results = ida.search(hqlString); for (Object obj : results) { String type = (String) obj; types.add(type); } } catch (Exception e) { logger.error("Problem to retrieve all function types. " + e); throw new RuntimeException( "Problem to retrieve all function types. "); } finally { ida.close(); } return types; } public List<CharacterizationTypeBean> getAllCharacterizationTypes() throws Exception { List<CharacterizationTypeBean> charTypes = new ArrayList<CharacterizationTypeBean>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); String query = "select distinct category, has_action, indent_level, category_order from def_characterization_category order by category_order"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("HAS_ACTION", Hibernate.INTEGER); queryObj.addScalar("INDENT_LEVEL", Hibernate.INTEGER); queryObj.addScalar("CATEGORY_ORDER", Hibernate.INTEGER); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); boolean hasAction = ((Integer) objarr[1] == 0) ? false : true; int indentLevel = (Integer) objarr[2]; CharacterizationTypeBean charType = new CharacterizationTypeBean( type, indentLevel, hasAction); charTypes.add(charType); } } catch (Exception e) { logger .error("Problem to retrieve all characterization types. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion types. "); } finally { hda.close(); } return charTypes; } public Map<String, SortedSet<String>> getDerivedDataCategoryMap( String characterizationName) throws Exception { Map<String, SortedSet<String>> categoryMap = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select category.name, datumName.name from DerivedBioAssayDataCategory category left join category.datumNameCollection datumName where datumName.datumParsed=false and category.characterizationName='" + characterizationName + "'"; List results = ida.search(hqlString); SortedSet<String> datumNames = null; for (Object obj : results) { String categoryName = ((Object[]) obj)[0].toString(); String datumName = ((Object[]) obj)[1].toString(); if (categoryMap.get(categoryName) != null) { datumNames = categoryMap.get(categoryName); } else { datumNames = new TreeSet<String>(); categoryMap.put(categoryName, datumNames); } datumNames.add(datumName); } } catch (Exception e) { logger .error("Problem to retrieve all derived bioassay data categories. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay data categories."); } finally { ida.close(); } return categoryMap; } public List<String> getDerivedDatumNames(String characterizationName) throws Exception { List<String> datumNames = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct datumName.name from DerivedBioAssayDataCategory category left join category.datumNameCollection datumName where datumName.datumParsed=false and category.characterizationName='" + characterizationName + "' order by datumName.name"; List results = ida.search(hqlString); for (Object obj : results) { String datumName = obj.toString(); datumNames.add(datumName); } } catch (Exception e) { logger .error("Problem to retrieve all derived bioassay datum names. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay datum names."); } finally { ida.close(); } return datumNames; } public List<String> getDerivedDataCategories(String characterizationName) throws Exception { List<String> categories = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct category.name from DerivedBioAssayDataCategory category left join category.datumNameCollection datumName where datumName.datumParsed=false and category.characterizationName='" + characterizationName + "' order by category.name"; List results = ida.search(hqlString); for (Object obj : results) { String category = obj.toString(); categories.add(category); } } catch (Exception e) { logger .error("Problem to retrieve all derived bioassay data categories. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay data categories."); } finally { ida.close(); } return categories; } }
package gov.nih.nci.calab.service.security; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.AuthorizationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.authentication.helper.EncryptedRDBMSHelper; import gov.nih.nci.security.authorization.domainobjects.Group; import gov.nih.nci.security.authorization.domainobjects.ProtectionElement; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroupRoleContext; import gov.nih.nci.security.authorization.domainobjects.Role; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.dao.GroupSearchCriteria; import gov.nih.nci.security.dao.ProtectionElementSearchCriteria; import gov.nih.nci.security.dao.ProtectionGroupSearchCriteria; import gov.nih.nci.security.dao.RoleSearchCriteria; import gov.nih.nci.security.dao.SearchCriteria; import gov.nih.nci.security.dao.UserSearchCriteria; import gov.nih.nci.security.exceptions.CSException; import gov.nih.nci.security.exceptions.CSObjectNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.servlet.http.HttpSession; import org.apache.struts.tiles.beans.MenuItem; /** * This class takes care of authentication and authorization of a user * * @author Pansu * */ public class UserService { private AuthenticationManager authenticationManager = null; private AuthorizationManager authorizationManager = null; private UserProvisioningManager userManager = null; private String applicationName = null; public UserService(String applicationName) throws CSException { this.applicationName = applicationName; this.authenticationManager = SecurityServiceProvider .getAuthenticationManager(applicationName); this.authorizationManager = SecurityServiceProvider .getAuthorizationManager(applicationName); this.userManager = SecurityServiceProvider .getUserProvisioningManager(applicationName); } public UserBean getUserBean(String userLogin) { User user = authorizationManager.getUser(userLogin); return new UserBean(user); // userManger.getUser(userLoginId); } public boolean isAdmin(String user) { boolean adminStatus = authorizationManager.checkOwnership(user, applicationName); return adminStatus; } public boolean isUserInGroup(UserBean user, String groupName) throws Exception { Set groups = userManager.getGroups(user.getUserId()); for (Object obj : groups) { Group group = (Group) obj; if (group.getGroupName().equalsIgnoreCase(groupName) || group.getGroupName().startsWith(groupName)) { return true; } } return false; } public boolean accessProtectionGroup(UserBean user, String protectionGroupName) { try { Set<ProtectionGroupRoleContext> protectionGroupRoleContexts = userManager .getProtectionGroupRoleContextForUser(user.getUserId()); for (ProtectionGroupRoleContext context : protectionGroupRoleContexts) { ProtectionGroup pg = context.getProtectionGroup(); while (pg.getParentProtectionGroup() != null) { if (pg.getParentProtectionGroup().getProtectionGroupName() .trim().equalsIgnoreCase(protectionGroupName)) { return true; } pg = pg.getParentProtectionGroup(); } } } catch (CSObjectNotFoundException e) { return false; } return false; } /** * Check whether the given user has the given privilege on the given * protection element * * @param user * @param protectionElementObjectId * @param privilege * @return * @throws CSException */ public boolean checkPermission(UserBean user, String protectionElementObjectId, String privilege) throws CSException { boolean status = false; status = authorizationManager.checkPermission(user.getLoginName(), protectionElementObjectId, privilege); return status; } /** * Check whether the given user has execute privilege on the given * protection element * * @param user * @param protectionElementObjectId * @return * @throws CSException */ public boolean checkExecutePermission(UserBean user, String protectionElementObjectId) throws CSException { return checkPermission(user, protectionElementObjectId, "EXECUTE"); } /** * Check whether the given user has read privilege on the given protection * element * * @param user * @param protectionElementObjectId * @return * @throws CSException */ public boolean checkReadPermission(UserBean user, String protectionElementObjectId) throws CSException { return checkPermission(user, protectionElementObjectId, "READ"); } /** * Check whether user can execute the menuItems in session, each defined as * a protection element using UPT tool. The excluded menuItems are not * checked. * * @param session * @throws CSException */ public void setFilteredMenuItem(HttpSession session) throws CSException { if (session.getAttribute("filteredItems") != null) { return; } List<MenuItem> filteredItems = new ArrayList<MenuItem>(); List<MenuItem> items = (List) session.getAttribute("items"); UserBean user = (UserBean) session.getAttribute("user"); if (user != null) { for (MenuItem item : items) { // make sure change menu item values to lower case since // pre-defined // pes and pgs in the UPT tool are entered as lower case and // CSM API is case sensitive boolean executeStatus = checkExecutePermission(user, item .getValue().toLowerCase()); if (executeStatus) { filteredItems.add(item); } } session.setAttribute("filteredItems", filteredItems); } } public void updatePassword(String loginName, String newPassword) throws Exception { User user = authorizationManager.getUser(loginName); java.util.Map options = SecurityServiceProvider .getLoginModuleOptions(CalabConstants.CSM_APP_NAME); String encryptedPassword = EncryptedRDBMSHelper.encrypt(newPassword, (String) options.get("hashAlgorithm")); user.setPassword(encryptedPassword); userManager.modifyUser(user); } /* * return all users in the database */ public List<UserBean> getAllUsers() throws Exception { List<UserBean> users = new ArrayList<UserBean>(); User dummy = new User(); dummy.setLoginName("*"); SearchCriteria sc = new UserSearchCriteria(dummy); List results = userManager.getObjects(sc); for (Object obj : results) { User doUser = (User) obj; users.add(new UserBean(doUser)); } return users; } /* * return all user groups in the database */ public List<String> getAllGroups() throws Exception { List<String> groups = new ArrayList<String>(); Group dummy = new Group(); dummy.setGroupName("*"); SearchCriteria sc = new GroupSearchCriteria(dummy); List results = userManager.getObjects(sc); for (Object obj : results) { Group doGroup = (Group) obj; groups.add(doGroup.getGroupName()); } return groups; } /* * return all user groups in the database */ public List<String> getAllVisibilityGroups() throws Exception { List<String> groups = getAllGroups(); //filter out the ones starting with NCL List<String>filteredGroups=new ArrayList<String>(); for(String groupName: groups) { if (!groupName.startsWith("NCL")) { filteredGroups.add(groupName); } } return filteredGroups; } public String getApplicationName() { return applicationName; } public AuthenticationManager getAuthenticationManager() { return authenticationManager; } public AuthorizationManager getAuthorizationManager() { return authorizationManager; } public UserProvisioningManager getUserManager() { return userManager; } public Group getGroup(String groupName) throws Exception { Group group = new Group(); group.setGroupName(groupName); SearchCriteria sc = new GroupSearchCriteria(group); List results = userManager.getObjects(sc); Group doGroup = null; for (Object obj : results) { doGroup = (Group) obj; break; } return doGroup; } public Role getRole(String roleName) throws Exception { Role role = new Role(); role.setName(roleName); SearchCriteria sc = new RoleSearchCriteria(role); List results = userManager.getObjects(sc); Role doRole = null; for (Object obj : results) { doRole = (Role) obj; break; } return doRole; } public ProtectionElement getProtectionElement(String objectId) throws Exception { ProtectionElement pe = new ProtectionElement(); pe.setObjectId(objectId); pe.setProtectionElementName(objectId); SearchCriteria sc = new ProtectionElementSearchCriteria(pe); List results = userManager.getObjects(sc); ProtectionElement doPE = null; for (Object obj : results) { doPE = (ProtectionElement) obj; break; } if (doPE == null) { authorizationManager.createProtectionElement(pe); return pe; } return doPE; } public ProtectionGroup getProtectionGroup(String protectionGroupName) throws Exception { ProtectionGroup pg = new ProtectionGroup(); pg.setProtectionGroupName(protectionGroupName); SearchCriteria sc = new ProtectionGroupSearchCriteria(pg); List results = userManager.getObjects(sc); ProtectionGroup doPG = null; for (Object obj : results) { doPG = (ProtectionGroup) obj; break; } if (doPG == null) { userManager.createProtectionGroup(pg); return pg; } return doPG; } public void assignProtectionElementToProtectionGroup(ProtectionElement pe, ProtectionGroup pg) throws Exception { Set assignedPGs = authorizationManager.getProtectionGroups(pe .getProtectionElementId().toString()); for (Object obj : assignedPGs) { if (((ProtectionGroup) obj).equals(pg)) { return; } } authorizationManager.assignProtectionElement(pg .getProtectionGroupName(), pe.getObjectId()); } public void secureObject(String objectName, String groupName, String roleName) throws Exception { // create protection element ProtectionElement pe = getProtectionElement(objectName); // create protection group ProtectionGroup pg = getProtectionGroup(objectName); // assign protection element to protection group if not already exists assignProtectionElementToProtectionGroup(pe, pg); // get group and role Group group = getGroup(groupName); Role role = getRole(roleName); if (group != null && role != null) { String[] roleIds = new String[] { role.getId().toString() }; userManager.assignGroupRoleToProtectionGroup(pg .getProtectionGroupId().toString(), group.getGroupId() .toString(), roleIds); } else { if (group == null) { throw new CalabException("No such group defined in CSM: " + groupName); } if (role == null) { throw new CalabException("No such role defined in CSM: " + roleName); } } } public List<ParticleBean> getFilteredParticles(UserBean user, List<ParticleBean> particles) throws Exception { List<ParticleBean> filteredParticles = new ArrayList<ParticleBean>(); for (ParticleBean particle : particles) { boolean status = checkReadPermission(user, particle.getSampleName()); if (status) { filteredParticles.add(particle); } } return filteredParticles; } }
package com.cloud.configuration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.cloud.agent.AgentManager; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.ha.HighAvailabilityManager; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.NetworkManager; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.server.ManagementServer; import com.cloud.storage.StorageManager; import com.cloud.storage.allocator.StoragePoolAllocator; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.vm.UserVmManager; public enum Config { // Alert AlertEmailAddresses("Alert", ManagementServer.class, String.class, "alert.email.addresses", null, "Comma separated list of email addresses used for sending alerts.", null), AlertEmailSender("Alert", ManagementServer.class, String.class, "alert.email.sender", null, "Sender of alert email (will be in the From header of the email).", null), AlertSMTPHost("Alert", ManagementServer.class, String.class, "alert.smtp.host", null, "SMTP hostname used for sending out email alerts.", null), AlertSMTPPassword("Alert", ManagementServer.class, String.class, "alert.smtp.password", null, "Password for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null), AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertWait("Alert", AgentManager.class, Integer.class, "alert.wait", null, "Seconds to wait before alerting on a disconnected agent", null), // Storage StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null), StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null), MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null), TotalRetries("Storage", AgentManager.class, Integer.class, "total.retries", "4", "The number of times each command sent to a host should be retried in case of failure.", null), // Network GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null), //MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null), NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null), GuestDomainSuffix("Network", AgentManager.class, String.class, "guest.domain.suffix", "cloud.internal", "Default domain name for vms inside virtualized networks fronted by router", null), DirectNetworkNoDefaultRoute("Network", ManagementServer.class, Boolean.class, "direct.network.no.default.route", "false", "Direct Network Dhcp Server should not send a default route", "true/false"), OvsNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.vlan.network", "false", "enable/disable vlan remapping of open vswitch network", null), OvsTunnelNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.tunnel.network", "false", "enable/disable open vswitch tunnel network(no vlan)", null), VmNetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "vm.network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in User vm's default network.", null), //VPN RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null), RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null), RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null), // Usage CapacityCheckPeriod("Usage", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null), StorageAllocatedCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.allocated.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", null), StorageCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", null), CPUCapacityThreshold("Usage", ManagementServer.class, Float.class, "cpu.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available.", null), MemoryCapacityThreshold("Usage", ManagementServer.class, Float.class, "memory.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available.", null), PublicIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "public.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of public IP address space utilization above which alerts will be sent.", null), PrivateIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "private.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of private IP address space utilization above which alerts will be sent.", null), // Console Proxy ConsoleProxyCapacityStandby("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacity.standby", "10", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)", null), ConsoleProxyCapacityScanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacityscan.interval", "30000", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity", null), ConsoleProxyCmdPort("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cmd.port", "8001", "Console proxy command port that is used to communicate with management server", null), ConsoleProxyRestart("Console Proxy", AgentManager.class, Boolean.class, "consoleproxy.restart", "true", "Console proxy restart flag, defaulted to true", null), ConsoleProxyUrlDomain("Console Proxy", AgentManager.class, String.class, "consoleproxy.url.domain", "realhostip.com", "Console proxy url domain", null), ConsoleProxyLoadscanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.loadscan.interval", "10000", "The time interval(in milliseconds) to scan console proxy working-load info", null), ConsoleProxyRamSize("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.ram.size", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE), "RAM size (in MB) used to create new console proxy VMs", null), ConsoleProxyCpuMHz("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cpu.mhz", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_CPUMHZ), "CPU speed (in MHz) used to create new console proxy VMs", null), ConsoleProxySessionMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.max", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_CAPACITY), "The max number of viewer sessions console proxy is configured to serve for", null), ConsoleProxySessionTimeout("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.timeout", "300000", "Timeout(in milliseconds) that console proxy tries to maintain a viewer session before it times out the session for no activity", null), ConsoleProxyDisableRpFilter("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.disable.rpfilter", "true", "disable rp_filter on console proxy VM public interface", null), ConsoleProxyLaunchMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.launch.max", "10", "maximum number of console proxy instances per zone can be launched", null), ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "console proxy service management state", null), ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "last console proxy service management state", null), // Snapshots SnapshotHourlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.hourly", "8", "Maximum hourly snapshots for a volume", null), SnapshotDailyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.daily", "8", "Maximum daily snapshots for a volume", null), SnapshotWeeklyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.weekly", "8", "Maximum weekly snapshots for a volume", null), SnapshotMonthlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.monthly", "8", "Maximum monthly snapshots for a volume", null), SnapshotPollInterval("Snapshots", SnapshotManager.class, Integer.class, "snapshot.poll.interval", "300", "The time interval in seconds when the management server polls for snapshots to be scheduled.", null), SnapshotDeltaMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.delta.max", "16", "max delta snapshots between two full snapshots.", null), // Advanced JobExpireMinutes("Advanced", ManagementServer.class, String.class, "job.expire.minutes", "1440", "Time (in minutes) for async-jobs to be kept in system", null), JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null), AccountCleanupInterval("Advanced", ManagementServer.class, Integer.class, "account.cleanup.interval", "86400", "The interval (in seconds) between cleanup for removed accounts", null), AllowPublicUserTemplates("Advanced", ManagementServer.class, Integer.class, "allow.public.user.templates", "true", "If false, users will not be able to create public templates.", null), InstanceName("Advanced", AgentManager.class, String.class, "instance.name", "VM", "Name of the deployment instance.", null), ExpungeDelay("Advanced", UserVmManager.class, Integer.class, "expunge.delay", "86400", "Determines how long (in seconds) to wait before actually expunging destroyed vm. The default value = the default value of expunge.interval", null), ExpungeInterval("Advanced", UserVmManager.class, Integer.class, "expunge.interval", "86400", "The interval (in seconds) to wait before running the expunge thread.", null), ExpungeWorkers("Advanced", UserVmManager.class, Integer.class, "expunge.workers", "1", "Number of workers performing expunge ", null), ExtractURLCleanUpInterval("Advanced", ManagementServer.class, Integer.class, "extract.url.cleanup.interval", "120", "The interval (in seconds) to wait before cleaning up the extract URL's ", null), HostStatsInterval("Advanced", ManagementServer.class, Integer.class, "host.stats.interval", "60000", "The interval (in milliseconds) when host stats are retrieved from agents.", null), HostRetry("Advanced", AgentManager.class, Integer.class, "host.retry", "2", "Number of times to retry hosts for creating a volume", null), IntegrationAPIPort("Advanced", ManagementServer.class, Integer.class, "integration.api.port", "8096", "Defaul API port", null), InvestigateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "investigate.retry.interval", "60", "Time (in seconds) between VM pings when agent is disconnected", null), MigrateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "migrate.retry.interval", "120", "Time (in seconds) between migration retries", null), PingInterval("Advanced", AgentManager.class, Integer.class, "ping.interval", "60", "Ping interval in seconds", null), PingTimeout("Advanced", AgentManager.class, Float.class, "ping.timeout", "2.5", "Multiplier to ping.interval before announcing an agent has timed out", null), Port("Advanced", AgentManager.class, Integer.class, "port", "8250", "Port to listen on for agent connection.", null), RouterCpuMHz("Advanced", NetworkManager.class, Integer.class, "router.cpu.mhz", String.valueOf(VirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null), RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null), RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null), RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null), StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null), StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null), StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval (in seconds) to wait before running the storage cleanup thread.", null), StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null), UpdateWait("Advanced", AgentManager.class, Integer.class, "update.wait", "600", "Time to wait (in seconds) before alerting on a updating agent", null), Wait("Advanced", AgentManager.class, Integer.class, "wait", "1800", "Time in seconds to wait for control commands to return", null), XapiWait("Advanced", AgentManager.class, Integer.class, "xapiwait", "600", "Time (in seconds) to wait for XAPI to return", null), CmdsWait("Advanced", AgentManager.class, Integer.class, "cmd.wait", "7200", "Time (in seconds) to wait for some heavy time-consuming commands", null), Workers("Advanced", AgentManager.class, Integer.class, "workers", "5", "Number of worker threads.", null), MountParent("Advanced", ManagementServer.class, String.class, "mount.parent", "/var/lib/cloud/mnt", "The mount point on the Management Server for Secondary Storage.", null), SystemVMUseLocalStorage("Advanced", ManagementServer.class, Boolean.class, "system.vm.use.local.storage", "false", "Indicates whether to use local storage pools or shared storage pools for system VMs.", null), SystemVMAutoReserveCapacity("Advanced", ManagementServer.class, Boolean.class, "system.vm.auto.reserve.capacity", "true", "Indicates whether or not to automatically reserver system VM standby capacity.", null), CPUOverprovisioningFactor("Advanced", ManagementServer.class, String.class, "cpu.overprovisioning.factor", "1", "Used for CPU overprovisioning calculation; available CPU will be (actualCpuCapacity * cpu.overprovisioning.factor)", null), LinkLocalIpNums("Advanced", ManagementServer.class, Integer.class, "linkLocalIp.nums", "10", "The number of link local ip that needed by domR(in power of 2)", null), HypervisorList("Advanced", ManagementServer.class, String.class, "hypervisor.list", HypervisorType.KVM + "," + HypervisorType.XenServer + "," + HypervisorType.VMware + "," + HypervisorType.BareMetal, "The list of hypervisors that this deployment will use.", "hypervisorList"), ManagementHostIPAdr("Advanced", ManagementServer.class, String.class, "host", "localhost", "The ip address of management server", null), ManagementNetwork("Advanced", ManagementServer.class, String.class, "management.network.cidr", null, "The cidr of management server network", null), EventPurgeDelay("Advanced", ManagementServer.class, Integer.class, "event.purge.delay", "15", "Events older than specified number days will be purged. Set this value to 0 to never delete events", null), UseLocalStorage("Premium", ManagementServer.class, Boolean.class, "use.local.storage", "false", "Should we use the local storage if it's available?", null), SecStorageVmRamSize("Advanced", AgentManager.class, Integer.class, "secstorage.vm.ram.size", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE), "RAM size (in MB) used to create new secondary storage vms", null), SecStorageVmCpuMHz("Advanced", AgentManager.class, Integer.class, "secstorage.vm.cpu.mhz", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_CPUMHZ), "CPU speed (in MHz) used to create new secondary storage vms", null), MaxTemplateAndIsoSize("Advanced", ManagementServer.class, Long.class, "max.template.iso.size", "50", "The maximum size for a downloaded template or ISO (in GB).", null), SecStorageAllowedInternalDownloadSites("Advanced", ManagementServer.class, String.class, "secstorage.allowed.internal.sites", null, "Comma separated list of cidrs internal to the datacenter that can host template download servers", null), SecStorageEncryptCopy("Advanced", ManagementServer.class, Boolean.class, "secstorage.encrypt.copy", "false", "Use SSL method used to encrypt copy traffic between zones", "true,false"), SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null), SecStorageCapacityStandby("Advanced", AgentManager.class, Integer.class, "secstorage.capacity.standby", "10", "The minimal number of command execution sessions that system is able to serve immediately(standby capacity)", null), SecStorageSessionMax("Advanced", AgentManager.class, Integer.class, "secstorage.session.max", "50", "The max number of command execution sessions that a SSVM can handle", null), SecStorageCmdExecutionTimeMax("Advanced", AgentManager.class, Integer.class, "secstorage.cmd.execution.time.max", "30", "The max command execution time in minute", null), DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"), DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null), CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"), NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null), NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null), HostCapacityCheckerWait("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.wait", "3600", "Time (in seconds) to wait before starting host capacity background checker", null), HostCapacityCheckerInterval("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.interval", "3600", "Time (in seconds) to wait before recalculating host's capacity", null), CapacitySkipcountingHours("Advanced", ManagementServer.class, Integer.class, "capacity.skipcounting.hours", "3600", "Time (in seconds) to wait before release VM's cpu and memory when VM in stopped state", null), VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null), VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null), ControlCidr("Advanced", ManagementServer.class, String.class, "control.cidr", "169.254.0.0/16", "Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods", null), ControlGateway("Advanced", ManagementServer.class, String.class, "control.gateway", "169.254.0.1", "gateway for the control network traffic", null), UseUserConcentratedPodAllocation("Advanced", ManagementServer.class, Boolean.class, "use.user.concentrated.pod.allocation", "true", "If true, deployment planner applies the user concentration heuristic during VM resource allocation", "true,false"), HostCapacityTypeToOrderClusters("Advanced", ManagementServer.class, String.class, "host.capacityType.to.order.clusters", "CPU", "The host capacity type (CPU or RAM) is used by deployment planner to order clusters during VM resource allocation", "CPU,RAM"), EndpointeUrl("Advanced", ManagementServer.class, String.class, "endpointe.url", "http://localhost:8080/client/api", "Endpointe Url", "The endpoint callback URL"), // XenServer VmAllocationAlgorithm("Advanced", ManagementServer.class, String.class, "vm.allocation.algorithm", "random", "If 'random', hosts within a pod will be randomly considered for VM/volume allocation. If 'firstfit', they will be considered on a first-fit basis.", null), XenPublicNetwork("Network", ManagementServer.class, String.class, "xen.public.network.device", null, "[ONLY IF THE PUBLIC NETWORK IS ON A DEDICATED NIC]:The network name label of the physical device dedicated to the public network on a XenServer host", null), XenStorageNetwork1("Network", ManagementServer.class, String.class, "xen.storage.network.device1", "cloud-stor1", "Specify when there are storage networks", null), XenStorageNetwork2("Network", ManagementServer.class, String.class, "xen.storage.network.device2", "cloud-stor2", "Specify when there are storage networks", null), XenPrivateNetwork("Network", ManagementServer.class, String.class, "xen.private.network.device", null, "Specify when the private network name is different", null), NetworkGuestCidrLimit("Network", NetworkManager.class, Integer.class, "network.guest.cidr.limit", "22", "size limit for guest cidr; can't be less than this value", null), XenMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.version", "3.3.1", "Minimum Xen version", null), XenProductMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.product.version", "0.1.1", "Minimum XenServer version", null), XenXapiMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.xapi.version", "1.3", "Minimum Xapi Tool Stack version", null), XenMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.version", "3.4.2", "Maximum Xen version", null), XenProductMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.product.version", "5.6.0", "Maximum XenServer version", null), XenXapiMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.xapi.version", "1.3", "Maximum Xapi Tool Stack version", null), XenSetupMultipath("Advanced", ManagementServer.class, String.class, "xen.setup.multipath", "false", "Setup the host to do multipath", null), XenBondStorageNic("Advanced", ManagementServer.class, String.class, "xen.bond.storage.nics", null, "Attempt to bond the two networks if found", null), XenHeartBeatInterval("Advanced", ManagementServer.class, Integer.class, "xen.heartbeat.interval", "60", "heartbeat to use when implementing XenServer Self Fencing", null), XenGuestNetwork("Advanced", ManagementServer.class, String.class, "xen.guest.network.device", null, "Specify for guest network name label", null), // VMware VmwarePrivateNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.private.vswitch", null, "Specify the vSwitch on host for private network", null), VmwarePublicNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null), VmwareGuestNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.guest.vswitch", null, "Specify the vSwitch on host for guest network", null), VmwareServiceConsole("Advanced", ManagementServer.class, String.class, "vmware.service.console", "Service Console", "Specify the service console network name (ESX host only)", null), // KVM KvmPublicNetwork("Advanced", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null), KvmPrivateNetwork("Advanced", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null), KvmGuestNetwork("Advanced", ManagementServer.class, String.class, "kvm.guest.network.device", null, "Specify the private bridge on host for private network", null), // Premium UsageExecutionTimezone("Premium", ManagementServer.class, String.class, "usage.execution.timezone", null, "The timezone to use for usage job execution time", null), UsageStatsJobAggregationRange("Premium", ManagementServer.class, Integer.class, "usage.stats.job.aggregation.range", "1440", "The range of time for aggregating the user statistics specified in minutes (e.g. 1440 for daily, 60 for hourly.", null), UsageStatsJobExecTime("Premium", ManagementServer.class, String.class, "usage.stats.job.exec.time", "00:15", "The time at which the usage statistics aggregation job will run as an HH24:MM time, e.g. 00:30 to run at 12:30am.", null), EnableUsageServer("Premium", ManagementServer.class, Boolean.class, "enable.usage.server", "true", "Flag for enabling usage", null), DirectNetworkStatsInterval("Premium", ManagementServer.class, Integer.class, "direct.network.stats.interval", "86400", "Interval (in seconds) to collect stats from Traffic Monitor", null), // Hidden UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null), CreatePoolsInPod("Hidden", ManagementServer.class, Boolean.class, "xen.create.pools.in.pod", "false", "Should we automatically add XenServers into pools that are inside a Pod", null), CloudIdentifier("Hidden", ManagementServer.class, String.class, "cloud.identifier", null, "A unique identifier for the cloud.", null), SSOKey("Hidden", ManagementServer.class, String.class, "security.singlesignon.key", null, "A Single Sign-On key used for logging into the cloud", null), SSOAuthTolerance("Advanced", ManagementServer.class, Long.class, "security.singlesignon.tolerance.millis", "300000", "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.", null), //NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"), HashKey("Hidden", ManagementServer.class, String.class, "security.hash.key", null, "for generic key-ed hash", null), RouterRamSize("Hidden", NetworkManager.class, Integer.class, "router.ram.size", "128", "Default RAM for router VM (in MB).", null), VmOpWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.op.wait.interval", "120", "Time (in seconds) to wait before checking if a previous operation has succeeded", null), VmOpLockStateRetry("Advanced", ManagementServer.class, Integer.class, "vm.op.lock.state.retry", "5", "Times to retry locking the state of a VM for operations", "-1 means try forever"), VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"), VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"), VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"), DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null), TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"), // Account Default Limits DefaultMaxAccountUserVms("Account Defaults", ManagementServer.class, Long.class, "max.account.user.vms", "20", "The default maximum number of user VMs that can be deployed for an account", null), DefaultMaxAccountPublicIPs("Account Defaults", ManagementServer.class, Long.class, "max.account.public.ips", "20", "The default maximum number of public IPs that can be consumed by an account", null), DefaultMaxAccountTemplates("Account Defaults", ManagementServer.class, Long.class, "max.account.templates", "20", "The default maximum number of templates that can be deployed for an account", null), DefaultMaxAccountSnapshots("Account Defaults", ManagementServer.class, Long.class, "max.account.snapshots", "20", "The default maximum number of snapshots that can be created for an account", null), DefaultMaxAccountVolumes("Account Defaults", ManagementServer.class, Long.class, "max.account.volumes", "20", "The default maximum number of volumes that can be created for an account", null), DirectAgentLoadSize("Advanced", ManagementServer.class, Integer.class, "direct.agent.load.size", "16", "The number of direct agents to load each time", null); private final String _category; private final Class<?> _componentClass; private final Class<?> _type; private final String _name; private final String _defaultValue; private final String _description; private final String _range; private static final HashMap<String, List<Config>> _configs = new HashMap<String, List<Config>>(); static { // Add categories _configs.put("Alert", new ArrayList<Config>()); _configs.put("Storage", new ArrayList<Config>()); _configs.put("Snapshots", new ArrayList<Config>()); _configs.put("Network", new ArrayList<Config>()); _configs.put("Usage", new ArrayList<Config>()); _configs.put("Console Proxy", new ArrayList<Config>()); _configs.put("Advanced", new ArrayList<Config>()); _configs.put("Premium", new ArrayList<Config>()); _configs.put("Developer", new ArrayList<Config>()); _configs.put("Hidden", new ArrayList<Config>()); _configs.put("Account Defaults", new ArrayList<Config>()); // Add values into HashMap for (Config c : Config.values()) { String category = c.getCategory(); List<Config> currentConfigs = _configs.get(category); currentConfigs.add(c); _configs.put(category, currentConfigs); } } private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range) { _category = category; _componentClass = componentClass; _type = type; _name = name; _defaultValue = defaultValue; _description = description; _range = range; } public String getCategory() { return _category; } public String key() { return _name; } public String getDescription() { return _description; } public String getDefaultValue() { return _defaultValue; } public Class<?> getType() { return _type; } public Class<?> getComponentClass() { return _componentClass; } public String getComponent() { if (_componentClass == ManagementServer.class) { return "management-server"; } else if (_componentClass == AgentManager.class) { return "AgentManager"; } else if (_componentClass == UserVmManager.class) { return "UserVmManager"; } else if (_componentClass == HighAvailabilityManager.class) { return "HighAvailabilityManager"; } else if (_componentClass == StoragePoolAllocator.class) { return "StorageAllocator"; } else { return "none"; } } public String getRange() { return _range; } @Override public String toString() { return _name; } public static List<Config> getConfigs(String category) { return _configs.get(category); } public static Config getConfig(String name) { List<String> categories = getCategories(); for (String category : categories) { List<Config> currentList = getConfigs(category); for (Config c : currentList) { if (c.key().equals(name)) { return c; } } } return null; } public static List<String> getCategories() { Object[] keys = _configs.keySet().toArray(); List<String> categories = new ArrayList<String>(); for (Object key : keys) { categories.add((String) key); } return categories; } }
package com.couchbase.lite; import com.couchbase.lite.internal.RevisionInternal; import com.couchbase.lite.util.Log; import junit.framework.Assert; import org.apache.commons.io.IOUtils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class ApiTest extends LiteTestCase { static void createDocuments(Database db, int n) { //TODO should be changed to use db.runInTransaction for (int i=0; i<n; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testDatabase"); properties.put("sequence", i); createDocumentWithProperties(db, properties); } }; static Document createDocumentWithProperties(Database db, Map<String,Object> properties) { Document doc = db.createDocument(); Assert.assertNotNull(doc); Assert.assertNull(doc.getCurrentRevisionId()); Assert.assertNull(doc.getCurrentRevision()); Assert.assertNotNull("Document has no ID", doc.getId()); // 'untitled' docs are no longer untitled (8/10/12) try{ doc.putProperties(properties); } catch( Exception e){ assertTrue("can't create new document in db:"+db.getName() + " with properties:"+ properties.toString(), false); } Assert.assertNotNull(doc.getId()); Assert.assertNotNull(doc.getCurrentRevisionId()); Assert.assertNotNull(doc.getUserProperties()); Assert.assertEquals(db.getDocument(doc.getId()), doc); return doc; } //SERVER & DOCUMENTS public void testAPIManager() { Manager manager = this.manager; Assert.assertTrue(manager!=null); for(String dbName : manager.getAllDatabaseNames()){ Database db = manager.getDatabase(dbName); Log.i(TAG, "Database '" + dbName + "':" + db.getDocumentCount() + " documents"); } ManagerOptions options= new ManagerOptions(true, false); Manager roManager=new Manager(new File(manager.getDirectory()), options); Assert.assertTrue(roManager!=null); Database db =roManager.getDatabase("foo"); Assert.assertNull(db); List<String> dbNames=manager.getAllDatabaseNames(); Assert.assertFalse(dbNames.contains("foo")); Assert.assertTrue(dbNames.contains(DEFAULT_TEST_DB)); } public void testCreateDocument() { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateDocument"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); String docID=doc.getId(); assertTrue("Invalid doc ID: " +docID , docID.length()>10); String currentRevisionID=doc.getCurrentRevisionId(); assertTrue("Invalid doc revision: " +docID , currentRevisionID.length()>10); assertEquals(doc.getUserProperties(), properties); assertEquals(db.getDocument(docID), doc); db.clearDocumentCache();// so we can load fresh copies Document doc2 = db.getExistingDocument(docID); assertEquals(doc2.getId(), docID); assertEquals(doc2.getCurrentRevisionId(), currentRevisionID); assertNull(db.getExistingDocument("b0gus")); } public void testCreateRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); SavedRevision rev1 = doc.getCurrentRevision(); assertTrue(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertNull(rev1.getAttachments()); // Test -createRevisionWithProperties: Map<String,Object> properties2 = new HashMap<String,Object>(properties); properties2.put("tag", 4567); SavedRevision rev2 = rev1.createRevision(properties2); assertNotNull("Put failed", rev2); assertTrue("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); assertEquals(rev2.getId(), doc.getCurrentRevisionId()); assertNotNull(rev2.arePropertiesAvailable()); assertEquals(rev2.getUserProperties(), properties2); assertEquals(rev2.getDocument(), doc); assertEquals(rev2.getProperty("_id"), doc.getId()); assertEquals(rev2.getProperty("_rev"), rev2.getId()); // Test -createRevision: UnsavedRevision newRev = rev2.createRevision(); assertNull(newRev.getId()); assertEquals(newRev.getParentRevision(), rev2); assertEquals(newRev.getParentRevisionId(), rev2.getId()); List<SavedRevision> listRevs=new ArrayList<SavedRevision>(); listRevs.add(rev1); listRevs.add(rev2); assertEquals(newRev.getRevisionHistory(), listRevs); assertEquals(newRev.getProperties(), rev2.getProperties()); assertEquals(newRev.getUserProperties(), rev2.getUserProperties()); Map<String,Object> userProperties=new HashMap<String, Object>(); userProperties.put("because", "NoSQL"); newRev.setUserProperties(userProperties); assertEquals(newRev.getUserProperties(), userProperties); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("because", "NoSQL"); expectProperties.put("_id", doc.getId()); expectProperties.put("_rev", rev2.getId()); assertEquals(newRev.getProperties(),expectProperties); SavedRevision rev3 = newRev.save(); assertNotNull(rev3); assertEquals(rev3.getUserProperties(), newRev.getUserProperties()); } public void testCreateNewRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=db.createDocument(); UnsavedRevision newRev =doc.createRevision(); Document newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertNull(newRev.getParentRevisionId()); assertNull(newRev.getParentRevision()); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("_id", doc.getId()); assertEquals(expectProperties, newRev.getProperties()); assertTrue(!newRev.isDeletion()); assertEquals(newRev.getSequence(), 0); //ios support another approach to set properties:: //newRev.([@"testName"] = @"testCreateRevisions"; //newRev[@"tag"] = @1337; newRev.setUserProperties(properties); assertEquals(newRev.getUserProperties(), properties); SavedRevision rev1 = newRev.save(); assertNotNull("Save 1 failed", rev1); assertEquals(doc.getCurrentRevision(), rev1); assertNotNull(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertNull(rev1.getParentRevisionId()); assertNull(rev1.getParentRevision()); newRev = rev1.createRevision(); newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertEquals(rev1.getId(), newRev.getParentRevisionId()); assertEquals(rev1, newRev.getParentRevision()); assertEquals(rev1.getProperties(), newRev.getProperties()); assertEquals(rev1.getUserProperties(), newRev.getUserProperties()); assertNotNull(!newRev.isDeletion()); // we can't add/modify one property as on ios. need to add separate method? // newRev[@"tag"] = @4567; properties.put("tag", 4567); newRev.setUserProperties(properties); SavedRevision rev2 = newRev.save(); assertNotNull( "Save 2 failed", rev2); assertEquals(doc.getCurrentRevision(), rev2); assertNotNull(rev2.getId().startsWith("2-")); assertEquals(2, rev2.getSequence()); assertEquals(rev1.getId(), rev2.getParentRevisionId()); assertEquals(rev1, rev2.getParentRevision()); assertNotNull("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); // Add a deletion/tombstone revision: newRev = doc.createRevision(); assertEquals(rev2.getId(), newRev.getParentRevisionId()); assertEquals(rev2, newRev.getParentRevision()); newRev.setIsDeletion(true); SavedRevision rev3 = newRev.save(); assertNotNull("Save 3 failed", rev3); assertEquals(doc.getCurrentRevision(), rev3); assertNotNull("Unexpected revID " + rev3.getId(), rev3.getId().startsWith("3-")); assertEquals(3, rev3.getSequence()); assertTrue(rev3.isDeletion()); assertTrue(doc.isDeleted()); db.getDocumentCount(); Document doc2 = db.getExistingDocument(doc.getId()); // BUG ON IOS! assertNull(doc2); } //API_SaveMultipleDocuments on IOS //API_SaveMultipleUnsavedDocuments on IOS //API_DeleteMultipleDocuments commented on IOS public void testDeleteDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testDeleteDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertTrue(!doc.isDeleted()); assertTrue(!doc.getCurrentRevision().isDeletion()); assertTrue(doc.delete()); assertTrue(doc.isDeleted()); assertNotNull(doc.getCurrentRevision().isDeletion()); } public void testPurgeDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testPurgeDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertNotNull(doc); assertNotNull(doc.purge()); Document redoc = db.getCachedDocument(doc.getId()); assertNull(redoc); } public void testAllDocuments() throws Exception{ Database db = startDatabase(); int kNDocs = 5; createDocuments(db, kNDocs); // clear the cache so all documents/revisions will be re-fetched: db.clearDocumentCache(); Log.i(TAG," Query query = db.createAllDocumentsQuery(); //query.prefetch = YES; Log.i(TAG, "Getting all documents: " + query); QueryEnumerator rows = query.run(); assertEquals(rows.getCount(), kNDocs); int n = 0; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); Log.i(TAG, " --> " + row); Document doc = row.getDocument(); assertNotNull("Couldn't get doc from query", doc ); assertNotNull("QueryRow should have preloaded revision contents", doc.getCurrentRevision().arePropertiesAvailable()); Log.i(TAG, " Properties =" + doc.getProperties()); assertNotNull("Couldn't get doc properties", doc.getProperties()); assertEquals(doc.getProperty("testName"), "testDatabase"); n++; } assertEquals(n, kNDocs); } public void testLocalDocs() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("foo", "bar"); Database db = startDatabase(); Map<String,Object> props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Couldn't put new local doc", db.putLocalDocument(properties, "dock")); props = db.getExistingLocalDocument("dock"); assertEquals(props.get("foo"), "bar"); Map<String,Object> newProperties = new HashMap<String, Object>(); newProperties.put("FOOO", "BARRR"); assertNotNull("Couldn't update local doc", db.putLocalDocument(newProperties, "dock")); props = db.getExistingLocalDocument("dock"); assertNull(props.get("foo")); assertEquals(props.get("FOOO"), "BARRR"); assertNotNull("Couldn't delete local doc", db.deleteLocalDocument("dock")); props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Second delete should have failed", !db.deleteLocalDocument("dock")); //TODO issue: deleteLocalDocument should return error.code( see ios) } // HISTORY public void testHistory() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "test06_History"); properties.put("tag", 1); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); String rev1ID = doc.getCurrentRevisionId(); Log.i(TAG, "1st revision: "+ rev1ID); assertNotNull("1st revision looks wrong: " + rev1ID, rev1ID.startsWith("1-")); assertEquals(doc.getUserProperties(), properties); properties = new HashMap<String, Object>(); properties.putAll(doc.getProperties()); properties.put("tag", 2); assertNotNull(!properties.equals(doc.getProperties())); assertNotNull(doc.putProperties(properties)); String rev2ID = doc.getCurrentRevisionId(); Log.i(TAG, "rev2ID" + rev2ID); assertNotNull("2nd revision looks wrong:" + rev2ID, rev2ID.startsWith("2-")); List<SavedRevision> revisions = doc.getRevisionHistory(); Log.i(TAG, "Revisions = " + revisions); assertEquals(revisions.size(), 2); SavedRevision rev1 = revisions.get(0); assertEquals(rev1.getId(), rev1ID); Map<String,Object> gotProperties = rev1.getProperties(); assertEquals(gotProperties.get("tag"), 1); SavedRevision rev2 = revisions.get(1); assertEquals(rev2.getId(), rev2ID); assertEquals(rev2, doc.getCurrentRevision()); gotProperties = rev2.getProperties(); assertEquals(gotProperties.get("tag"), 2); List<SavedRevision> tmp = new ArrayList<SavedRevision>(); tmp.add(rev2); assertEquals(doc.getConflictingRevisions(), tmp); assertEquals(doc.getLeafRevisions(), tmp); } /* TODO conflict is not supported now? public void testConflict() throws Exception{ Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, prop); SavedRevision rev1 = doc.getCurrentRevision(); Map<String,Object> properties = doc.getProperties(); properties.put("tag", 2); SavedRevision rev2a = doc.putProperties(properties); properties = rev1.getProperties(); properties.put("tag", 3); UnsavedRevision newRev = rev1.createRevision(); newRev.setProperties(properties); //TODO ? saveAllowingConflict not found, see ios SavedRevision rev2b = newRev.save(); assertNotNull("Failed to create a a conflict", rev2b); List<SavedRevision> confRevs = new ArrayList<SavedRevision>(); confRevs.add(rev2b); confRevs.add(rev2a); assertEquals(doc.getConflictingRevisions(), confRevs); assertEquals(doc.getLeafRevisions(), confRevs); SavedRevision defaultRev, otherRev; if (rev2a.getId().compareTo(rev2b.getId()) > 0) { defaultRev = rev2a; otherRev = rev2b; } else { defaultRev = rev2b; otherRev = rev2a; } assertEquals(doc.getCurrentRevision(), defaultRev); Query query = db.createAllDocumentsQuery(); // TODO allDocsMode? query.allDocsMode = kCBLShowConflicts; QueryEnumerator rows = query.getRows(); assertEquals(rows.getCount(), 1); QueryRow row = rows.getRow(0); // TODO conflictingRevisions? List<SavedRevision> revs = row.conflictingRevisions; assertEquals(revs.size(), 2); assertEquals(revs.get(0), defaultRev); assertEquals(revs.get(1), otherRev); } */ //ATTACHMENTS public void testAttachments() throws Exception, IOException { Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testAttachments"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); SavedRevision rev = doc.getCurrentRevision(); assertEquals(rev.getAttachments().size(), 0); assertEquals(rev.getAttachmentNames().size(), 0); assertNull(rev.getAttachment("index.html")); String content = "This is a test attachment!"; ByteArrayInputStream body = new ByteArrayInputStream(content.getBytes()); UnsavedRevision rev2 = doc.createRevision(); rev2.setAttachment("index.html", "text/plain; charset=utf-8", body); SavedRevision rev3 = rev2.save(); assertNotNull(rev3); assertEquals(rev3.getAttachments().size(), 1); assertEquals(rev3.getAttachmentNames().size(), 1); Attachment attach = rev3.getAttachment("index.html"); assertNotNull(attach); assertEquals(doc, attach.getDocument()); assertEquals("index.html", attach.getName()); List<String> attNames = new ArrayList<String>(); attNames.add("index.html"); assertEquals(rev3.getAttachmentNames(), attNames); assertEquals("text/plain; charset=utf-8", attach.getContentType()); assertEquals(IOUtils.toString(attach.getContent(), "UTF-8"), content); assertEquals(attach.getLength(), content.getBytes().length); // TODO getcontentURL was not implemented? // NSURL* bodyURL = attach.getcontentURL; // assertNotNull(bodyURL.isFileURL); // assertEquals([NSData dataWithContentsOfURL: bodyURL], body); // UnsavedRevision *newRev = [rev3 createRevision]; // [newRev removeAttachmentNamed: attach.name]; // CBLRevision* rev4 = [newRev save: &error]; // assertNotNull(!error); // assertNotNull(rev4); // assertEquals([rev4.attachmentNames count], (NSUInteger)0); } //CHANGE TRACKING //VIEWS public void testCreateView() throws Exception{ Database db = startDatabase(); View view = db.getView("vu"); assertNotNull(view); assertEquals(view.getDatabase(), db); assertEquals(view.getName(), "vu"); assertNull(view.getMap()); assertNull(view.getReduce()); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); assertNotNull(view.getMap() != null); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); assertEquals(query.getDatabase(), db); query.setStartKey(23); query.setEndKey(33); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getKey(), expectedKey); assertEquals(row.getSequenceNumber(), expectedKey+1); ++expectedKey; } } //API_RunSlowView commented on IOS public void testValidation() throws Exception{ Database db = startDatabase(); db.setValidation("uncool", new ValidationBlock() { @Override public boolean validate(RevisionInternal newRevision, ValidationContext context) { { if (newRevision.getPropertyForKey("groovy") ==null) { context.setErrorMessage("uncool"); return false; } return true; } } }); Map<String,Object> properties = new HashMap<String,Object>(); properties.put("groovy", "right on"); properties.put( "foo", "bar"); Document doc = db.createDocument(); assertNotNull(doc.putProperties(properties)); properties = new HashMap<String,Object>(); properties.put( "foo", "bar"); doc = db.createDocument(); try{ assertNull(doc.putProperties(properties)); } catch (CouchbaseLiteException e){ //TODO assertEquals(e.getCBLStatus().getCode(), Status.FORBIDDEN); // assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet } } public void testViewWithLinkedDocs() throws Exception{ Database db = startDatabase(); int kNDocs = 50; Document[] docs = new Document[50]; String lastDocID = ""; for (int i=0; i<kNDocs; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("sequence", i); properties.put("prev", lastDocID); Document doc = createDocumentWithProperties(db, properties); docs[i]=doc; lastDocID = doc.getId(); } Query query = db.slowQuery(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), new Object[]{"_id" , document.get("prev") }); } }); query.setStartKey(23); query.setEndKey(33); query.setPrefetch(true); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(rows.getCount(), 11); int rowNumber = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getKey(), rowNumber); Document prevDoc = docs[rowNumber]; assertEquals(row.getDocumentId(), prevDoc.getId()); assertEquals(row.getDocument(), prevDoc); ++rowNumber; } } /* public void testLiveQuery() throws Exception{ final Database db = startDatabase(); View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); int kNDocs = 50; createDocuments(db, kNDocs); final CBLLiveQuery query = view.createQuery().toLiveQuery();; query.setStartKey(23); query.setEndKey(33); Log.i(TAG, "Created " + query); assertNull(query.getRows()); Log.i(TAG, "Waiting for live query to update..."); boolean finished = false; query.start(); //TODO temp solution for infinite loop int i=0; while (!finished && i <100){ QueryEnumerator rows = query.getRows(); Log.i(TAG, "Live query rows = " + rows); i++; if (rows != null) { assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getDocument().getDatabase(), db); assertEquals(row.getKey(), expectedKey); ++expectedKey; } finished = true; } } query.stop(); assertTrue("Live query timed out!", finished); } public void testAsyncViewQuery() throws Exception, InterruptedException { final Database db = startDatabase(); View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); query.setStartKey(23); query.setEndKey(33); final boolean[] finished = {false}; final Thread curThread = Thread.currentThread(); query.runAsync(new Query.QueryCompleteListener() { @Override public void queryComplete(QueryEnumerator rows, Throwable error) { Log.i(TAG, "Async query finished!"); //TODO Failed! assertEquals(Thread.currentThread().getId(), curThread.getId()); assertNotNull(rows); assertNull(error); assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getDocument().getDatabase(), db); assertEquals(row.getKey(), expectedKey); ++expectedKey; } finished[0] = true; } }); Log.i(TAG, "Waiting for async query to finish..."); assertTrue("Async query timed out!", finished[0]); } // Make sure that a database's map/reduce functions are shared with the shadow database instance // running in the background server. public void testSharedMapBlocks() throws Exception, ExecutionException, InterruptedException { Manager mgr = new Manager(new File(getInstrumentation().getContext().getFilesDir(), "API_SharedMapBlocks")); Database db = mgr.getDatabase("db"); db.open(); db.setFilter("phil", new CBLFilterDelegate() { @Override public boolean filter(RevisionInternal revision, Map<String, Object> params) { return true; } }); db.setValidation("val", new ValidationBlock() { @Override public boolean validate(RevisionInternal newRevision, ValidationContext context) { return true; } }); View view = db.getView("view"); boolean ok = view.setMapAndReduce(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { }}, new CBLReducer() { @Override public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) { return null; } }, "1"); assertNotNull("Couldn't set map/reduce", ok); final Mapper map = view.getMap(); final CBLReducer reduce = view.getReduce(); final CBLFilterDelegate filter = db.getFilter("phil"); final ValidationBlock validation = db.getValidation("val"); Future result = mgr.runAsync("db", new DatabaseAsyncFunction() { @Override public boolean performFunction(Database database) { assertNotNull(database); View serverView = database.getExistingView("view"); assertNotNull(serverView); assertEquals(database.getFilter("phil"), filter); assertEquals(database.getValidation("val"), validation); assertEquals(serverView.getMap(), map); assertEquals(serverView.getReduce(), reduce); return true; } }); Thread.sleep(20000); assertEquals(result.get(), true); db.close(); mgr.close(); } */ public void testChangeUUID() throws Exception{ Manager mgr = new Manager(new File(getInstrumentation().getContext().getFilesDir(), "ChangeUUID"), Manager.DEFAULT_OPTIONS); Database db = mgr.getDatabase("db"); db.open(); String pub = db.publicUUID(); String priv = db.privateUUID(); assertTrue(pub.length() > 10); assertTrue(priv.length() > 10); assertTrue("replaceUUIDs failed", db.replaceUUIDs()); assertFalse(pub.equals(db.publicUUID())); assertFalse(priv.equals(db.privateUUID())); mgr.close(); } }
package com.sun.star.wizards.form; import com.sun.star.awt.XCheckBox; import com.sun.star.awt.XRadioButton; import com.sun.star.beans.PropertyValue; import com.sun.star.wizards.common.Helper; import com.sun.star.wizards.common.Properties; import com.sun.star.wizards.ui.UnoDialog; import com.sun.star.wizards.ui.WizardDialog; import com.sun.star.wizards.ui.UIConsts; public class DataEntrySetter{ WizardDialog CurUnoDialog; short curtabindex; XRadioButton optNewDataOnly; XRadioButton optDisplayAllData; XCheckBox chknomodification; XCheckBox chknodeletion; XCheckBox chknoaddition; public DataEntrySetter(WizardDialog _CurUnoDialog) { this.CurUnoDialog = _CurUnoDialog; curtabindex = (short) (FormWizard.SODATAPAGE * 100); Integer IDataStep = new Integer(FormWizard.SODATAPAGE); String sNewDataOnly = CurUnoDialog.m_oResource.getResText(UIConsts.RID_FORM + 44); String sDisplayAllData = CurUnoDialog.m_oResource.getResText(UIConsts.RID_FORM + 46); String sNoModification = CurUnoDialog.m_oResource.getResText(UIConsts.RID_FORM + 47); // AllowUpdates String sNoDeletion = CurUnoDialog.m_oResource.getResText(UIConsts.RID_FORM + 48); // AllowDeletes String sNoAddition = CurUnoDialog.m_oResource.getResText(UIConsts.RID_FORM + 49); // AlowInserts String sdontdisplayExistingData = CurUnoDialog.m_oResource.getResText(UIConsts.RID_FORM + 45); optNewDataOnly = CurUnoDialog.insertRadioButton("optNewDataOnly", "toggleCheckBoxes", this, new String[] {"Height", "HelpURL", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width"}, new Object[] {UIConsts.INTEGERS[8], "HID:34461", sNewDataOnly, new Integer(98), new Integer(25),IDataStep, new Short(curtabindex++), new Integer(195)} ); optDisplayAllData = CurUnoDialog.insertRadioButton("optDisplayAllData", "toggleCheckBoxes", this, new String[] {"Height", "HelpURL", "Label", "PositionX", "PositionY", "State", "Step", "TabIndex", "Width"}, new Object[] {UIConsts.INTEGERS[8],"HID:34462", sDisplayAllData, new Integer(98), new Integer(50), new Short((short)1),IDataStep, new Short(curtabindex++), new Integer(197)} ); chknomodification = CurUnoDialog.insertCheckBox("chknomodification", null, new String[] {"Height", "HelpURL", "Label", "PositionX", "PositionY", "State", "Step", "TabIndex", "Width"}, new Object[] {UIConsts.INTEGERS[8], "HID:34463", sNoModification, new Integer(108), new Integer(62), new Short((short)0),IDataStep, new Short(curtabindex++), new Integer(189)} ); chknodeletion = CurUnoDialog.insertCheckBox("chknodeletion", null, new String[] {"Height", "HelpURL", "Label", "PositionX", "PositionY", "State", "Step", "TabIndex", "Width"}, new Object[] {UIConsts.INTEGERS[8], "HID:34464", sNoDeletion, new Integer(108), new Integer(74), new Short((short)0),IDataStep, new Short(curtabindex++), new Integer(189)} ); chknoaddition = CurUnoDialog.insertCheckBox("chknoaddition", null, new String[] {"Height", "HelpURL", "Label", "PositionX", "PositionY", "State", "Step", "TabIndex", "Width"}, new Object[] {UIConsts.INTEGERS[8], "HID:34465", sNoAddition, new Integer(108), new Integer(86), new Short((short)0),IDataStep, new Short(curtabindex++), new Integer(191)} ); CurUnoDialog.insertLabel("lbldontdisplayExistingData", new String[] {"Height", "Label", "PositionX", "PositionY", "Step", "TabIndex", "Width"}, new Object[] { new Integer(8), sdontdisplayExistingData, new Integer(108), new Integer(33),IDataStep, new Short(curtabindex++), new Integer(134)} ); } public PropertyValue[] getFormProperties(){ PropertyValue[] retProperties; if (optDisplayAllData.getState()){ retProperties = new PropertyValue[3]; boolean bAllowUpdates = (((Short) Helper.getUnoPropertyValue(UnoDialog.getModel(chknomodification), "State")).shortValue()) != 1; boolean bAllowDeletes = (((Short) Helper.getUnoPropertyValue(UnoDialog.getModel(chknodeletion), "State")).shortValue()) != 1; boolean bAllowInserts = (((Short) Helper.getUnoPropertyValue(UnoDialog.getModel(chknoaddition), "State")).shortValue()) != 1; retProperties[0] = Properties.createProperty("AllowUpdates", new Boolean(bAllowUpdates)); retProperties[1] = Properties.createProperty("AllowDeletes", new Boolean(bAllowDeletes)); retProperties[2] = Properties.createProperty("AllowInserts", new Boolean(bAllowInserts)); } else{ retProperties = new PropertyValue[1]; retProperties[0] = Properties.createProperty("IgnoreResult", new Boolean(true)); } return retProperties; } public void toggleCheckBoxes(){ boolean bdisplayalldata = optDisplayAllData.getState(); Helper.setUnoPropertyValue(UnoDialog.getModel(chknomodification), "Enabled", new Boolean(bdisplayalldata)); Helper.setUnoPropertyValue(UnoDialog.getModel(chknodeletion), "Enabled", new Boolean(bdisplayalldata)); Helper.setUnoPropertyValue(UnoDialog.getModel(chknoaddition), "Enabled", new Boolean(bdisplayalldata)); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wycs.io; import java.io.File; import java.math.BigInteger; import java.util.*; import wyautl.util.BigRational; import wybs.io.AbstractLexer; import wybs.io.Token; import wybs.lang.Attribute; import wybs.lang.Path; import wybs.lang.SyntacticElement; import wybs.lang.SyntaxError; import wybs.util.Pair; import wybs.util.Trie; import wycs.lang.*; import wycs.lang.WycsFile.Assert; import wycs.lang.WycsFile.Define; import wycs.lang.WycsFile.Function; public class WycsFileStructuredParser extends WycsFileClassicalParser { public final int SPACES_PER_TAB = 4; public WycsFileStructuredParser(String filename, List<Token> tokens) { super(filename,tokens); } @Override protected void parseImport(WycsFile wf) { super.parseImport(wf); matchEndOfLine(); } @Override protected void parseAssert(WycsFile wf) { int start = index; match("assert"); skipWhiteSpace(); String msg = null; if (matches(Token.String.class)) { Token.String s = match(Token.String.class); msg = s.text.substring(1,s.text.length()-1); } Expr condition; if(matches(":")) { match(":"); matchEndOfLine(); condition = parseBlock(0,new HashSet<String>(), new HashSet<String>()); } else { condition = parseCondition(new HashSet<String>(), new HashSet<String>()); } wf.add(wf.new Assert(msg, condition, sourceAttr(start, index - 1))); } @Override protected void parseFunction(WycsFile wf) { int start = index; match("function"); HashSet<String> environment = new HashSet<String>(); ArrayList<String> generics = new ArrayList<String>(); String name = parseGenericSignature(environment,generics); HashSet<String> genericSet = new HashSet<String>(generics); TypePattern from = parseTypePattern(genericSet); addNamedVariables(from,environment); // function! match("=>"); TypePattern to = parseTypePattern(genericSet); addNamedVariables(to, environment); Expr condition = null; if(matches("where")) { match("where"); match(":"); matchEndOfLine(); condition = parseBlock(0,genericSet, environment); } wf.add(wf.new Function(name, generics, from, to, condition, sourceAttr(start, index - 1))); } @Override protected void parseDefine(WycsFile wf) { int start = index; match("define"); HashSet<String> environment = new HashSet<String>(); ArrayList<String> generics = new ArrayList<String>(); String name = parseGenericSignature(environment, generics); HashSet<String> genericSet = new HashSet<String>(generics); TypePattern from = parseTypePattern(genericSet); addNamedVariables(from, environment); match("as"); match(":"); matchEndOfLine(); Expr condition = parseBlock(0,genericSet, environment); wf.add(wf.new Define(name, generics, from, condition, sourceAttr(start, index - 1))); } protected Expr parseBlock(int parentIndent, HashSet<String> generics, HashSet<String> environment) { int start = index; int indent = scanIndent(); if(indent <= parentIndent) { // empty block return Expr.Constant(Value.Bool(true)); } parentIndent = indent; ArrayList<Expr> constraints = new ArrayList<Expr>(); while(indent >= parentIndent && index < tokens.size()) { matchIndent(indent); constraints.add(parseStatement(indent,generics,environment)); indent = scanIndent(); } if(constraints.size() == 0) { return Expr.Constant(Value.Bool(true)); } else if(constraints.size() == 1) { return constraints.get(0); } else { Expr[] operands = constraints.toArray(new Expr[constraints.size()]); return Expr.Nary(Expr.Nary.Op.AND, operands, sourceAttr(start,index-1)); } } protected Expr parseStatement(int parentIndent, HashSet<String> generics, HashSet<String> environment) { if(matches("if")) { return parseIfThen(parentIndent,generics,environment); } else if(matches("forall")) { return parseSomeForAll(false,parentIndent,generics,environment); } else if(matches("some")) { return parseSomeForAll(true,parentIndent,generics,environment); } else if(matches("case")) { return parseCase(parentIndent,generics,environment); } else { Expr e = parseCondition(generics,environment); matchEndOfLine(); return e; } } protected Expr parseIfThen(int parentIndent, HashSet<String> generics, HashSet<String> environment) { int start = index; match("if"); match(":"); matchEndOfLine(); Expr condition = parseBlock(parentIndent, generics, environment); match("then"); match(":"); matchEndOfLine(); Expr body = parseBlock(parentIndent, generics, environment); return Expr.Binary(Expr.Binary.Op.IMPLIES, condition, body, sourceAttr(start, index - 1)); } protected Expr parseSomeForAll(boolean isSome, int parentIndent, HashSet<String> generics, HashSet<String> environment) { int start = index; if(isSome) { match("some"); } else { match("forall"); } match("("); ArrayList<Pair<TypePattern,Expr>> variables = new ArrayList<Pair<TypePattern,Expr>>(); boolean firstTime = true; while (!matches(")")) { if (!firstTime) { match(","); } else { firstTime = false; } TypePattern pattern = parseTypePatternUnionOrIntersection(generics); Expr src = null; if(matches("in",Token.sUC_ELEMENTOF)) { match("in",Token.sUC_ELEMENTOF); src = parseCondition(generics,environment); } addNamedVariables(pattern,environment); variables.add(new Pair<TypePattern,Expr>(pattern,src)); } match(")"); Expr body; if(matches(":")) { match(":"); matchEndOfLine(); body = parseBlock(parentIndent,generics,environment); } else { body = parseCondition(generics,environment); } Pair<TypePattern, Expr>[] varArray = variables .toArray(new Pair[variables.size()]); if (isSome) { return Expr.Exists(varArray, body, sourceAttr(start, index - 1)); } else { return Expr.ForAll(varArray, body, sourceAttr(start, index - 1)); } } protected Expr parseCase(int parentIndent, HashSet<String> generics, HashSet<String> environment) { int start = index; match("case"); match(":"); matchEndOfLine(); ArrayList<Expr> cases = new ArrayList<Expr>(); cases.add(parseBlock(parentIndent,generics,environment)); int indent = parentIndent; while(indent >= parentIndent && index < tokens.size()) { int tmp = index; matchIndent(indent); if(!matches("case")) { // breakout point index = tmp; // backtrack } match("case"); match(":"); matchEndOfLine(); cases.add(parseBlock(parentIndent,generics,environment)); indent = scanIndent(); } if(cases.size() == 0) { return Expr.Constant(Value.Bool(true)); } else if(cases.size() == 1) { return cases.get(0); } else { Expr[] operands = cases.toArray(new Expr[cases.size()]); return Expr.Nary(Expr.Nary.Op.OR, operands, sourceAttr(start,index-1)); } } protected int scanIndent() { int indent = 0; int i = index; while (i < tokens.size() && (tokens.get(i) instanceof Token.Spaces || tokens .get(i) instanceof Token.Tabs)) { Token token = tokens.get(i); if(token instanceof Token.Spaces) { indent += token.text.length(); } else { indent += token.text.length() * SPACES_PER_TAB; } i = i + 1; } return indent; } protected int matchIndent(int indent) { while (index < tokens.size() && (tokens.get(index) instanceof Token.Spaces || tokens .get(index) instanceof Token.Tabs)) { Token token = tokens.get(index); if(token instanceof Token.Spaces) { indent -= token.text.length(); } else { indent -= token.text.length() * SPACES_PER_TAB; } index = index + 1; if (indent < 0) { syntaxError("unexpected level of indentation", token); } } return indent; } protected void matchEndOfLine() { int start = index; Token lookahead = null; while (index < tokens.size() && (lookahead = tokens.get(index)) instanceof Token.Whitespace) { index = index + 1; if (lookahead instanceof Token.NewLine) { return; // done; } } if (index < tokens.size()) { syntaxError("expected end-of-line", lookahead); } else if (lookahead != null) { syntaxError("unexpected end-of-file", lookahead); } else { // This should always be safe since we only ever call matchEndOfLine // after having already matched something. syntaxError("unexpected end-of-file", tokens.get(start - 1)); } } }
package com.cloud.vm.dao; import java.util.Date; import java.util.List; import javax.ejb.Local; import org.apache.log4j.Logger; import com.cloud.uservm.UserVm; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.Attribute; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.NicVO; import com.cloud.vm.State; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.Event; @Local(value={UserVmDao.class}) public class UserVmDaoImpl extends GenericDaoBase<UserVmVO, Long> implements UserVmDao { public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class.getName()); protected final SearchBuilder<UserVmVO> RouterStateSearch; protected final SearchBuilder<UserVmVO> RouterIdSearch; protected final SearchBuilder<UserVmVO> AccountPodSearch; protected final SearchBuilder<UserVmVO> AccountDataCenterSearch; protected final SearchBuilder<UserVmVO> AccountSearch; protected final SearchBuilder<UserVmVO> HostSearch; protected final SearchBuilder<UserVmVO> LastHostSearch; protected final SearchBuilder<UserVmVO> HostUpSearch; protected final SearchBuilder<UserVmVO> HostRunningSearch; protected final SearchBuilder<UserVmVO> NameSearch; protected final SearchBuilder<UserVmVO> StateChangeSearch; protected final SearchBuilder<UserVmVO> GuestIpSearch; protected final SearchBuilder<UserVmVO> ZoneAccountGuestIpSearch; protected final SearchBuilder<UserVmVO> DestroySearch; protected SearchBuilder<UserVmVO> AccountDataCenterVirtualSearch; protected final Attribute _updateTimeAttr; protected UserVmDaoImpl() { AccountSearch = createSearchBuilder(); AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountSearch.done(); HostSearch = createSearchBuilder(); HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostSearch.done(); LastHostSearch = createSearchBuilder(); LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ); LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ); LastHostSearch.done(); HostUpSearch = createSearchBuilder(); HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN); HostUpSearch.done(); HostRunningSearch = createSearchBuilder(); HostRunningSearch.and("host", HostRunningSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostRunningSearch.and("state", HostRunningSearch.entity().getState(), SearchCriteria.Op.EQ); HostRunningSearch.done(); NameSearch = createSearchBuilder(); NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ); NameSearch.done(); RouterStateSearch = createSearchBuilder(); RouterStateSearch.and("router", RouterStateSearch.entity().getDomainRouterId(), SearchCriteria.Op.EQ); RouterStateSearch.done(); RouterIdSearch = createSearchBuilder(); RouterIdSearch.and("router", RouterIdSearch.entity().getDomainRouterId(), SearchCriteria.Op.EQ); RouterIdSearch.done(); AccountPodSearch = createSearchBuilder(); AccountPodSearch.and("account", AccountPodSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountPodSearch.and("pod", AccountPodSearch.entity().getPodId(), SearchCriteria.Op.EQ); AccountPodSearch.done(); AccountDataCenterSearch = createSearchBuilder(); AccountDataCenterSearch.and("account", AccountDataCenterSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountDataCenterSearch.and("dc", AccountDataCenterSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); AccountDataCenterSearch.done(); StateChangeSearch = createSearchBuilder(); StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ); StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ); StateChangeSearch.done(); GuestIpSearch = createSearchBuilder(); GuestIpSearch.and("dc", GuestIpSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); GuestIpSearch.and("ip", GuestIpSearch.entity().getGuestIpAddress(), SearchCriteria.Op.EQ); GuestIpSearch.and("states", GuestIpSearch.entity().getState(), SearchCriteria.Op.NIN); GuestIpSearch.done(); DestroySearch = createSearchBuilder(); DestroySearch.and("state", DestroySearch.entity().getState(), SearchCriteria.Op.IN); DestroySearch.and("updateTime", DestroySearch.entity().getUpdateTime(), SearchCriteria.Op.LT); DestroySearch.done(); ZoneAccountGuestIpSearch = createSearchBuilder(); ZoneAccountGuestIpSearch.and("dataCenterId", ZoneAccountGuestIpSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneAccountGuestIpSearch.and("accountId", ZoneAccountGuestIpSearch.entity().getAccountId(), SearchCriteria.Op.EQ); ZoneAccountGuestIpSearch.and("guestIpAddress", ZoneAccountGuestIpSearch.entity().getGuestIpAddress(), SearchCriteria.Op.EQ); ZoneAccountGuestIpSearch.done(); _updateTimeAttr = _allAttributes.get("updateTime"); assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; } public List<UserVmVO> listByAccountAndPod(long accountId, long podId) { SearchCriteria<UserVmVO> sc = AccountPodSearch.create(); sc.setParameters("account", accountId); sc.setParameters("pod", podId); return listIncludingRemovedBy(sc); } public List<UserVmVO> listByAccountAndDataCenter(long accountId, long dcId) { SearchCriteria<UserVmVO> sc = AccountDataCenterSearch.create(); sc.setParameters("account", accountId); sc.setParameters("dc", dcId); return listIncludingRemovedBy(sc); } @Override public List<UserVmVO> listBy(long routerId, State... states) { SearchCriteria<UserVmVO> sc = RouterStateSearch.create(); SearchCriteria<UserVmVO> ssc = createSearchCriteria(); sc.setParameters("router", routerId); for (State state: states) { ssc.addOr("state", SearchCriteria.Op.EQ, state.toString()); } sc.addAnd("state", SearchCriteria.Op.SC, ssc); return listIncludingRemovedBy(sc); } @Override public void updateVM(long id, String displayName, boolean enable) { UserVmVO vo = createForUpdate(); vo.setDisplayName(displayName); vo.setHaEnabled(enable); update(id, vo); } @Override public List<UserVmVO> listByRouterId(long routerId) { SearchCriteria<UserVmVO> sc = RouterIdSearch.create(); sc.setParameters("router", routerId); return listIncludingRemovedBy(sc); } @Override public boolean updateIf(UserVmVO vm, VirtualMachine.Event event, Long hostId) { if (s_logger.isDebugEnabled()) { s_logger.debug("UpdateIf called " + vm.toString() + " event " + event.toString() + " host " + hostId); } State oldState = vm.getState(); State newState = oldState.getNextState(event); Long oldHostId = vm.getHostId(); long oldDate = vm.getUpdated(); if (newState == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); } return false; } SearchCriteria<UserVmVO> sc = StateChangeSearch.create(); sc.setParameters("id", vm.getId()); sc.setParameters("states", oldState); sc.setParameters("host", vm.getHostId()); sc.setParameters("update", vm.getUpdated()); vm.incrUpdated(); UpdateBuilder ub = getUpdateBuilder(vm); if(newState == State.Running) { // save current running host id to last_host_id field ub.set(vm, "lastHostId", vm.getHostId()); } else if(newState == State.Expunging) { ub.set(vm, "lastHostId", null); } ub.set(vm, "state", newState); ub.set(vm, "hostId", hostId); ub.set(vm, _updateTimeAttr, new Date()); int result = update(vm, sc); if (result == 0 && s_logger.isDebugEnabled()) { UserVmVO vo = findById(vm.getId()); StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); str.append("} New Data: {Host=").append(vm.getHostId()).append("; State=").append(vm.getState().toString()).append("; updated=").append(vm.getUpdated()); str.append("} Stale Data: {Host=").append(oldHostId).append("; State=").append(oldState.toString()).append("; updated=").append(oldDate).append("}"); s_logger.debug(str.toString()); } return result > 0; } @Override public List<UserVmVO> findDestroyedVms(Date date) { SearchCriteria<UserVmVO> sc = DestroySearch.create(); sc.setParameters("state", State.Destroyed, State.Expunging, State.Error); sc.setParameters("updateTime", date); return listBy(sc); } public List<UserVmVO> listByAccountId(long id) { SearchCriteria<UserVmVO> sc = AccountSearch.create(); sc.setParameters("account", id); return listBy(sc); } public List<UserVmVO> listByHostId(Long id) { SearchCriteria<UserVmVO> sc = HostSearch.create(); sc.setParameters("host", id); return listBy(sc); } @Override public List<UserVmVO> listUpByHostId(Long hostId) { SearchCriteria<UserVmVO> sc = HostUpSearch.create(); sc.setParameters("host", hostId); sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging}); return listBy(sc); } public List<UserVmVO> listRunningByHostId(long hostId) { SearchCriteria<UserVmVO> sc = HostRunningSearch.create(); sc.setParameters("host", hostId); sc.setParameters("state", State.Running); return listBy(sc); } public UserVmVO findByName(String name) { SearchCriteria<UserVmVO> sc = NameSearch.create(); sc.setParameters("name", name); return findOneIncludingRemovedBy(sc); } @Override public List<UserVmVO> listVirtualNetworkInstancesByAcctAndZone(long accountId, long dcId, long networkId) { if (AccountDataCenterVirtualSearch == null) { NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class); SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); AccountDataCenterVirtualSearch = createSearchBuilder(); AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); AccountDataCenterVirtualSearch.done(); } SearchCriteria<UserVmVO> sc = AccountDataCenterVirtualSearch.create(); sc.setParameters("account", accountId); sc.setParameters("dc", dcId); sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); } @Override public List<UserVmVO> listVmsUsingGuestIpAddress(long dcId, String ipAddress) { SearchCriteria<UserVmVO> sc = GuestIpSearch.create(); sc.setParameters("dc", dcId); sc.setParameters("ip", ipAddress); sc.setParameters("states", new Object[] {State.Destroyed, State.Expunging}); return listBy(sc); } @Override public UserVm findByZoneAndAcctAndGuestIpAddress(long zoneId, long accountId, String ipAddress) { SearchCriteria<UserVmVO> sc = ZoneAccountGuestIpSearch.create(); sc.setParameters("dataCenterId", zoneId); sc.setParameters("accountId", accountId); sc.setParameters("guestIpAddress", ipAddress); return findOneBy(sc); } @Override public boolean updateState(State oldState, Event event, State newState, VMInstanceVO vm, Long hostId) { if (newState == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString()); } return false; } UserVmVO userVM = (UserVmVO)vm; SearchCriteria<UserVmVO> sc = StateChangeSearch.create(); sc.setParameters("id", userVM.getId()); sc.setParameters("states", oldState); sc.setParameters("host", userVM.getHostId()); sc.setParameters("update", userVM.getUpdated()); vm.incrUpdated(); UpdateBuilder ub = getUpdateBuilder(userVM); ub.set(userVM, "state", newState); ub.set(userVM, "hostId", hostId); ub.set(userVM, _updateTimeAttr, new Date()); int result = update(userVM, sc); if (result == 0 && s_logger.isDebugEnabled()) { UserVmVO vo = findById(userVM.getId()); StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString()); str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()); str.append("} Stale Data: {Host=").append(userVM.getHostId()).append("; State=").append(userVM.getState().toString()).append("; updated=").append(userVM.getUpdated()).append("}"); s_logger.debug(str.toString()); } return result > 0; } @Override public List<UserVmVO> listByLastHostId(Long hostId) { SearchCriteria<UserVmVO> sc = LastHostSearch.create(); sc.setParameters("lastHost", hostId); sc.setParameters("state", State.Stopped); return listBy(sc); } }
package com.cloud.vm.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ejb.Local; import org.apache.log4j.Logger; import com.cloud.api.response.NicResponse; import com.cloud.api.response.SecurityGroupResponse; import com.cloud.api.response.UserVmResponse; import com.cloud.user.Account; import com.cloud.uservm.UserVm; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.Attribute; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicVO; import com.cloud.vm.UserVmVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; @Local(value={UserVmDao.class}) public class UserVmDaoImpl extends GenericDaoBase<UserVmVO, Long> implements UserVmDao { public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class); protected final SearchBuilder<UserVmVO> AccountPodSearch; protected final SearchBuilder<UserVmVO> AccountDataCenterSearch; protected final SearchBuilder<UserVmVO> AccountSearch; protected final SearchBuilder<UserVmVO> HostSearch; protected final SearchBuilder<UserVmVO> LastHostSearch; protected final SearchBuilder<UserVmVO> HostUpSearch; protected final SearchBuilder<UserVmVO> HostRunningSearch; protected final SearchBuilder<UserVmVO> StateChangeSearch; protected final SearchBuilder<UserVmVO> AccountHostSearch; protected final SearchBuilder<UserVmVO> DestroySearch; protected SearchBuilder<UserVmVO> AccountDataCenterVirtualSearch; protected GenericSearchBuilder<UserVmVO, Long> CountByAccountPod; protected GenericSearchBuilder<UserVmVO, Long> CountByAccount; protected GenericSearchBuilder<UserVmVO, Long> PodsHavingVmsForAccount; protected SearchBuilder<UserVmVO> UserVmSearch; protected final Attribute _updateTimeAttr; private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND state = 'Running' OR state = 'Stopped' " + "GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC"; private static final String VM_DETAILS = "select account.account_name, account.type, domain.name, instance_group.id, instance_group.name," + "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " + "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " + "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " + "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " + "security_group.description, nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " + "networks.traffic_type, networks.guest_type, networks.is_default from vm_instance " + "left join account on vm_instance.account_id=account.id " + "left join domain on vm_instance.domain_id=domain.id " + "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " + "left join instance_group on instance_group_vm_map.group_id=instance_group.id " + "left join data_center on vm_instance.data_center_id=data_center.id " + "left join host on vm_instance.host_id=host.id " + "left join vm_template on vm_instance.vm_template_id=vm_template.id " + "left join vm_template iso on iso.id=? " + "left join service_offering on vm_instance.service_offering_id=service_offering.id " + "left join disk_offering on vm_instance.service_offering_id=disk_offering.id " + "left join volumes on vm_instance.id=volumes.instance_id " + "left join storage_pool on volumes.pool_id=storage_pool.id " + "left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " + "left join security_group on security_group_vm_map.security_group_id=security_group.id " + "left join nics on vm_instance.id=nics.instance_id " + "left join networks on nics.network_id=networks.id " + "where vm_instance.id=?"; protected final UserVmDetailsDaoImpl _detailsDao = ComponentLocator.inject(UserVmDetailsDaoImpl.class); protected UserVmDaoImpl() { AccountSearch = createSearchBuilder(); AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountSearch.done(); HostSearch = createSearchBuilder(); HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostSearch.done(); LastHostSearch = createSearchBuilder(); LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ); LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ); LastHostSearch.done(); HostUpSearch = createSearchBuilder(); HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN); HostUpSearch.done(); HostRunningSearch = createSearchBuilder(); HostRunningSearch.and("host", HostRunningSearch.entity().getHostId(), SearchCriteria.Op.EQ); HostRunningSearch.and("state", HostRunningSearch.entity().getState(), SearchCriteria.Op.EQ); HostRunningSearch.done(); AccountPodSearch = createSearchBuilder(); AccountPodSearch.and("account", AccountPodSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountPodSearch.and("pod", AccountPodSearch.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); AccountPodSearch.done(); AccountDataCenterSearch = createSearchBuilder(); AccountDataCenterSearch.and("account", AccountDataCenterSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountDataCenterSearch.and("dc", AccountDataCenterSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); AccountDataCenterSearch.done(); StateChangeSearch = createSearchBuilder(); StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ); StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ); StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ); StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ); StateChangeSearch.done(); DestroySearch = createSearchBuilder(); DestroySearch.and("state", DestroySearch.entity().getState(), SearchCriteria.Op.IN); DestroySearch.and("updateTime", DestroySearch.entity().getUpdateTime(), SearchCriteria.Op.LT); DestroySearch.done(); AccountHostSearch = createSearchBuilder(); AccountHostSearch.and("accountId", AccountHostSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountHostSearch.and("hostId", AccountHostSearch.entity().getHostId(), SearchCriteria.Op.EQ); AccountHostSearch.done(); CountByAccountPod = createSearchBuilder(Long.class); CountByAccountPod.select(null, Func.COUNT, null); CountByAccountPod.and("account", CountByAccountPod.entity().getAccountId(), SearchCriteria.Op.EQ); CountByAccountPod.and("pod", CountByAccountPod.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); CountByAccountPod.done(); CountByAccount = createSearchBuilder(Long.class); CountByAccount.select(null, Func.COUNT, null); CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ); CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ); CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN); CountByAccount.done(); _updateTimeAttr = _allAttributes.get("updateTime"); assert _updateTimeAttr != null : "Couldn't get this updateTime attribute"; } @Override public List<UserVmVO> listByAccountAndPod(long accountId, long podId) { SearchCriteria<UserVmVO> sc = AccountPodSearch.create(); sc.setParameters("account", accountId); sc.setParameters("pod", podId); return listIncludingRemovedBy(sc); } @Override public List<UserVmVO> listByAccountAndDataCenter(long accountId, long dcId) { SearchCriteria<UserVmVO> sc = AccountDataCenterSearch.create(); sc.setParameters("account", accountId); sc.setParameters("dc", dcId); return listIncludingRemovedBy(sc); } @Override public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData) { UserVmVO vo = createForUpdate(); vo.setDisplayName(displayName); vo.setHaEnabled(enable); vo.setGuestOSId(osTypeId); vo.setUserData(userData); update(id, vo); } @Override public List<UserVmVO> findDestroyedVms(Date date) { SearchCriteria<UserVmVO> sc = DestroySearch.create(); sc.setParameters("state", State.Destroyed, State.Expunging, State.Error); sc.setParameters("updateTime", date); return listBy(sc); } @Override public List<UserVmVO> listByAccountId(long id) { SearchCriteria<UserVmVO> sc = AccountSearch.create(); sc.setParameters("account", id); return listBy(sc); } @Override public List<UserVmVO> listByHostId(Long id) { SearchCriteria<UserVmVO> sc = HostSearch.create(); sc.setParameters("host", id); return listBy(sc); } @Override public List<UserVmVO> listUpByHostId(Long hostId) { SearchCriteria<UserVmVO> sc = HostUpSearch.create(); sc.setParameters("host", hostId); sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging}); return listBy(sc); } @Override public List<UserVmVO> listRunningByHostId(long hostId) { SearchCriteria<UserVmVO> sc = HostRunningSearch.create(); sc.setParameters("host", hostId); sc.setParameters("state", State.Running); return listBy(sc); } @Override public List<UserVmVO> listVirtualNetworkInstancesByAcctAndZone(long accountId, long dcId, long networkId) { if (AccountDataCenterVirtualSearch == null) { NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class); SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); AccountDataCenterVirtualSearch = createSearchBuilder(); AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ); AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); AccountDataCenterVirtualSearch.done(); } SearchCriteria<UserVmVO> sc = AccountDataCenterVirtualSearch.create(); sc.setParameters("account", accountId); sc.setParameters("dc", dcId); sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); } @Override public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) { if (UserVmSearch == null) { NicDao _nicDao = ComponentLocator.getLocator("management-server").getDao(NicDao.class); SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder(); nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL); UserVmSearch = createSearchBuilder(); UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN); UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); UserVmSearch.done(); } SearchCriteria<UserVmVO> sc = UserVmSearch.create(); if (states != null && states.length != 0) { sc.setParameters("states", (Object[]) states); } sc.setJoinParameters("nicSearch", "networkId", networkId); return listBy(sc); } @Override public List<UserVmVO> listByLastHostId(Long hostId) { SearchCriteria<UserVmVO> sc = LastHostSearch.create(); sc.setParameters("lastHost", hostId); sc.setParameters("state", State.Stopped); return listBy(sc); } @Override public List<UserVmVO> listByAccountIdAndHostId(long accountId, long hostId) { SearchCriteria<UserVmVO> sc = AccountHostSearch.create(); sc.setParameters("hostId", hostId); sc.setParameters("accountId", accountId); return listBy(sc); } @Override public void loadDetails(UserVmVO vm) { Map<String, String> details = _detailsDao.findDetails(vm.getId()); vm.setDetails(details); } @Override public void saveDetails(UserVmVO vm) { Map<String, String> details = vm.getDetails(); if (details == null) { return; } _detailsDao.persist(vm.getId(), details); } @Override public List<Long> listPodIdsHavingVmsforAccount(long zoneId, long accountId){ Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; List<Long> result = new ArrayList<Long>(); try { String sql = LIST_PODS_HAVING_VMS_FOR_ACCOUNT; pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, zoneId); pstmt.setLong(2, accountId); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { result.add(rs.getLong(1)); } return result; } catch (SQLException e) { throw new CloudRuntimeException("DB Exception on: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e); } catch (Throwable e) { throw new CloudRuntimeException("Caught: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e); } } @Override public UserVmResponse listVmDetails(UserVm userVm, boolean show_host){ Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; try { String sql = VM_DETAILS; pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, userVm.getIsoId() == null ? -1 : userVm.getIsoId()); pstmt.setLong(2, userVm.getId()); ResultSet rs = pstmt.executeQuery(); boolean is_data_center_security_group_enabled=false; Set<SecurityGroupResponse> securityGroupResponse = new HashSet<SecurityGroupResponse>(); Set<NicResponse> nicResponses = new HashSet<NicResponse>(); UserVmResponse userVmResponse = null; while (rs.next()) { if (userVmResponse==null){ userVmResponse=new UserVmResponse(); userVmResponse.setId(userVm.getId()); userVmResponse.setName(userVm.getInstanceName()); userVmResponse.setCreated(userVm.getCreated()); userVmResponse.setGuestOsId(userVm.getGuestOSId()); userVmResponse.setHaEnable(userVm.isHaEnabled()); if (userVm.getState() != null) { userVmResponse.setState(userVm.getState().toString()); } if (userVm.getDisplayName() != null) { userVmResponse.setDisplayName(userVm.getDisplayName()); } else { userVmResponse.setDisplayName(userVm.getHostName()); } //account.account_name, account.type, domain.name, instance_group.id, instance_group.name," userVmResponse.setAccountName(rs.getString("account.account_name")); userVmResponse.setDomainId(userVm.getDomainId()); userVmResponse.setDomainName(rs.getString("domain.name")); long grp_id = rs.getLong("instance_group.id"); if (grp_id > 0){ userVmResponse.setGroupId(grp_id); userVmResponse.setGroup(rs.getString("instance_group.name")); } //"data_center.id, data_center.name, host.id, host.name, vm_template.id, vm_template.name, vm_template.display_text, vm_template.enable_password, userVmResponse.setZoneId(rs.getLong("data_center.id")); userVmResponse.setZoneName(rs.getString("data_center.name")); if (show_host){ userVmResponse.setHostId(rs.getLong("host.id")); userVmResponse.setHostName(rs.getString("host.name")); } if (userVm.getHypervisorType() != null) { userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); } long template_id = rs.getLong("vm_template.id"); if (template_id > 0){ userVmResponse.setTemplateId(template_id); userVmResponse.setTemplateName(rs.getString("vm_template.name")); userVmResponse.setTemplateDisplayText(rs.getString("vm_template.display_text")); userVmResponse.setPasswordEnabled(rs.getBoolean("vm_template.enable_password")); } else { userVmResponse.setTemplateId(-1L); userVmResponse.setTemplateName("ISO Boot"); userVmResponse.setTemplateDisplayText("ISO Boot"); userVmResponse.setPasswordEnabled(false); } long iso_id = rs.getLong("iso.id"); if (iso_id > 0){ userVmResponse.setIsoId(iso_id); userVmResponse.setIsoName(rs.getString("iso.name")); } if (userVm.getPassword() != null) { userVmResponse.setPassword(userVm.getPassword()); } //service_offering.id, disk_offering.name, " //"service_offering.cpu, service_offering.speed, service_offering.ram_size, userVmResponse.setServiceOfferingId(rs.getLong("service_offering.id")); userVmResponse.setServiceOfferingName(rs.getString("disk_offering.name")); userVmResponse.setCpuNumber(rs.getInt("service_offering.cpu")); userVmResponse.setCpuSpeed(rs.getInt("service_offering.speed")); userVmResponse.setMemory(rs.getInt("service_offering.ram_size")); // volumes.device_id, volumes.volume_type, long vol_id = rs.getLong("volumes.id"); if (vol_id > 0){ userVmResponse.setRootDeviceId(rs.getLong("volumes.device_id")); userVmResponse.setRootDeviceType(rs.getString("volumes.volume_type")); // storage pool long pool_id = rs.getLong("storage_pool.id"); if (pool_id > 0){ userVmResponse.setRootDeviceType(rs.getString("storage_pool.pool_type")); } else { userVmResponse.setRootDeviceType("Not created"); } } is_data_center_security_group_enabled = rs.getBoolean("data_center.is_security_group_enabled"); } //security_group.id, security_group.name, security_group.description, , data_center.is_security_group_enabled if (is_data_center_security_group_enabled){ SecurityGroupResponse resp = new SecurityGroupResponse(); resp.setId(rs.getLong("security_group.id")); resp.setName(rs.getString("security_group.name")); resp.setDescription(rs.getString("security_group.description")); resp.setObjectName("securitygroup"); securityGroupResponse.add(resp); } //nics.id, nics.ip4_address, nics.gateway, nics.network_id, nics.netmask, nics. mac_address, nics.broadcast_uri, nics.isolation_uri, " + //"networks.traffic_type, networks.guest_type, networks.is_default from vm_instance, " long nic_id = rs.getLong("nics.id"); if (nic_id > 0){ NicResponse nicResponse = new NicResponse(); nicResponse.setId(nic_id); nicResponse.setIpaddress(rs.getString("nics.ip4_address")); nicResponse.setGateway(rs.getString("nics.gateway")); nicResponse.setNetmask(rs.getString("nics.netmask")); nicResponse.setNetworkid(rs.getLong("nics.network_id")); nicResponse.setMacAddress(rs.getString("nics.mac_address")); int account_type = rs.getInt("account.type"); if (account_type == Account.ACCOUNT_TYPE_ADMIN) { nicResponse.setBroadcastUri(rs.getString("nics.broadcast_uri")); nicResponse.setIsolationUri(rs.getString("nics.isolation_uri")); } nicResponse.setTrafficType(rs.getString("networks.traffic_type")); nicResponse.setType(rs.getString("networks.guest_type")); nicResponse.setIsDefault(rs.getBoolean("networks.is_default")); nicResponse.setObjectName("nic"); nicResponses.add(nicResponse); } } userVmResponse.setSecurityGroupList(new ArrayList<SecurityGroupResponse>(securityGroupResponse)); userVmResponse.setNics(new ArrayList<NicResponse>(nicResponses)); rs.close(); pstmt.close(); return userVmResponse; } catch (SQLException e) { throw new CloudRuntimeException("DB Exception on: " + VM_DETAILS, e); } catch (Throwable e) { throw new CloudRuntimeException("Caught: " + VM_DETAILS, e); } } @Override public Long countAllocatedVMsForAccount(long accountId) { SearchCriteria<Long> sc = CountByAccount.create(); sc.setParameters("account", accountId); sc.setParameters("type", VirtualMachine.Type.User); sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging}); return customSearch(sc, null).get(0); } }
// Depot library - a Java relational persistence library // 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.samskivert.depot.impl; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Set; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.samskivert.util.ArrayUtil; import com.samskivert.util.StringUtil; import com.samskivert.util.Tuple; import com.samskivert.jdbc.ColumnDefinition; import com.samskivert.jdbc.DatabaseLiaison; import com.samskivert.depot.DatabaseException; import com.samskivert.depot.Key; import com.samskivert.depot.PersistenceContext; import com.samskivert.depot.PersistentRecord; import com.samskivert.depot.SchemaMigration; import com.samskivert.depot.Stats; import com.samskivert.depot.annotation.Column; import com.samskivert.depot.annotation.Computed; import com.samskivert.depot.annotation.Entity; import com.samskivert.depot.annotation.FullTextIndex; import com.samskivert.depot.annotation.GeneratedValue; import com.samskivert.depot.annotation.Id; import com.samskivert.depot.annotation.Index; import com.samskivert.depot.annotation.TableGenerator; import com.samskivert.depot.annotation.Transient; import com.samskivert.depot.annotation.UniqueConstraint; import com.samskivert.depot.clause.QueryClause; import com.samskivert.depot.clause.OrderBy.Order; import com.samskivert.depot.expression.ColumnExp; import com.samskivert.depot.expression.SQLExpression; import com.samskivert.depot.impl.clause.CreateIndexClause; import static com.samskivert.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T extends PersistentRecord> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pClass, PersistenceContext context) { _pClass = pClass; Preconditions.checkArgument(!java.lang.reflect.Modifier.isAbstract(pClass.getModifiers()), "Can't handle reference to abstract record: " + pClass.getName()); Entity entity = pClass.getAnnotation(Entity.class); // see if this is a computed entity _computed = pClass.getAnnotation(Computed.class); if (_computed == null) { // if not, this class has a corresponding SQL table _tableName = DepotUtil.justClassName(_pClass); // see if there are Entity values specified if (entity != null) { if (entity.name().length() > 0) { _tableName = entity.name(); } } } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pClass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } boolean seenIdentityGenerator = false; // introspect on the class and create marshallers and indices for persistent fields List<ColumnExp> fields = Lists.newArrayList(); ListMultimap<String, Tuple<SQLExpression, Order>> namedFieldIndices = ArrayListMultimap.create(); ListMultimap<String, Tuple<SQLExpression, Order>> uniqueNamedFieldIndices = ArrayListMultimap.create(); for (Field field : _pClass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.warning("Failed to read schema version [class=" + _pClass + "].", e); } } // the field must be public, non-static and non-transient if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller<?> fm = FieldMarshaller.createMarshaller(field); _fields.put(field.getName(), fm); ColumnExp fieldColumn = new ColumnExp(_pClass, field.getName()); fields.add(fieldColumn); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = Lists.newArrayList(); } _pkColumns.add(fm); } // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // check if this field is auto-generated GeneratedValue gv = fm.getGeneratedValue(); if (gv != null) { // we can only do this on numeric fields Class<?> ftype = field.getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column: " + field.getName()); } switch(gv.strategy()) { case AUTO: case IDENTITY: if (seenIdentityGenerator) { throw new IllegalArgumentException( "Persistent records can have at most one AUTO/IDENTITY generator."); } _valueGenerators.put(field.getName(), new IdentityValueGenerator(gv, this, fm)); seenIdentityGenerator = true; break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _valueGenerators.put( field.getName(), new TableValueGenerator(generator, gv, this, fm)); break; case SEQUENCE: // TODO throw new IllegalArgumentException( "SEQUENCE key generation strategy not yet supported."); } } // check whether this field is indexed Index index = field.getAnnotation(Index.class); if (index != null) { String name = index.name().equals("") ? field.getName() + "Index" : index.name(); Tuple<SQLExpression, Order> entry = new Tuple<SQLExpression, Order>(fieldColumn, Order.ASC); if (index.unique()) { Preconditions.checkArgument(!namedFieldIndices.containsKey(index.name()), "All @Index for a particular name must be unique or non-unique"); uniqueNamedFieldIndices.put(name, entry); } else { Preconditions.checkArgument( !uniqueNamedFieldIndices.containsKey(index.name()), "All @Index for a particular name must be unique or non-unique"); namedFieldIndices.put(name, entry); } } // if this column is marked as unique, that also means we create an index Column column = field.getAnnotation(Column.class); if (column != null && column.unique()) { _indexes.add(buildIndex(field.getName() + "Index", true, fieldColumn)); } } for (String indexName : namedFieldIndices.keySet()) { _indexes.add(buildIndex(indexName, false, namedFieldIndices.get(indexName))); } for (String indexName : uniqueNamedFieldIndices.keySet()) { _indexes.add(buildIndex(indexName, true, uniqueNamedFieldIndices.get(indexName))); } // if we did not find a schema version field, freak out (but not for computed records, for // whom there is no table) if (_tableName != null && _schemaVersion <= 0) { throw new IllegalStateException( pClass.getName() + "." + SCHEMA_VERSION_FIELD + " must be greater than zero."); } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new ColumnExp[fields.size()]); // now check for @Entity annotations on the entire superclass chain Class<? extends PersistentRecord> iterClass = pClass.asSubclass(PersistentRecord.class); do { entity = iterClass.getAnnotation(Entity.class); if (entity != null) { // add any indices needed for uniqueness constraints for (UniqueConstraint constraint : entity.uniqueConstraints()) { ColumnExp[] colExps = new ColumnExp[constraint.fields().length]; int ii = 0; for (String field : constraint.fields()) { FieldMarshaller<?> fm = _fields.get(field); if (fm == null) { throw new IllegalArgumentException( "Unknown unique constraint field: " + field); } colExps[ii ++] = new ColumnExp(_pClass, field); } _indexes.add(buildIndex(constraint.name(), true, colExps)); } // add any explicit multicolumn or complex indices for (Index index : entity.indices()) { _indexes.add(buildIndex(index.name(), index.unique())); } // note any FTS indices for (FullTextIndex fti : entity.fullTextIndices()) { if (_fullTextIndexes.containsKey(fti.name())) { continue; } _fullTextIndexes.put(fti.name(), fti); } } iterClass = iterClass.getSuperclass().asSubclass(PersistentRecord.class); } while (PersistentRecord.class.isAssignableFrom(iterClass) && !PersistentRecord.class.equals(iterClass)); } /** * Returns the persistent class this is object is a marshaller for. */ public Class<T> getPersistentClass () { return _pClass; } /** * Returns the @Computed annotation definition of this entity, or null if none. */ public Computed getComputed () { return _computed; } /** * Returns the name of the table in which persistent instances of our class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns all the persistent fields of our class, in definition order. */ public ColumnExp[] getFieldNames () { return _allFields; } /** * Returns all the persistent fields that correspond to concrete table columns. */ public ColumnExp[] getColumnFieldNames () { return _columnFields; } public FullTextIndex getFullTextIndex (String name) { FullTextIndex fti = _fullTextIndexes.get(name); if (fti == null) { throw new IllegalStateException("Persistent class missing full text index " + "[class=" + _pClass + ", index=" + name + "]"); } return fti; } /** * Returns the {@link FieldMarshaller} for a named field on our persistent class. */ public FieldMarshaller<?> getFieldMarshaller (String fieldName) { return _fields.get(fieldName); } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns the {@link ValueGenerator} objects used to automatically generate field values for * us when a new record is inserted. */ public Iterable<ValueGenerator> getValueGenerators () { return _valueGenerators.values(); } /** * Return the names of the columns that constitute the primary key of our associated persistent * record. */ public ColumnExp[] getPrimaryKeyFields () { ColumnExp[] pkcols = new ColumnExp[_pkColumns.size()]; for (int ii = 0; ii < pkcols.length; ii ++) { pkcols[ii] = new ColumnExp(_pClass, _pkColumns.get(ii).getField().getName()); } return pkcols; } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. An exception is thrown if some of the fields are null and * some are not, or if the object does not declare a primary key. */ public Key<T> getPrimaryKey (Object object) { return getPrimaryKey(object, true); } /** * Returns a key configured with the primary key of the supplied object. If all the fields are * null, this method returns null. If some of the fields are null and some are not, an * exception is thrown. If the object does not declare a primary key and the second argument is * true, this method throws an exception; if it's false, the method returns null. */ public Key<T> getPrimaryKey (Object object, boolean requireKey) { if (requireKey) { checkHasPrimaryKey(); } else if (!hasPrimaryKey()) { return null; } try { Comparable<?>[] values = new Comparable<?>[_pkColumns.size()]; int nulls = 0, zeros = 0; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller<?> field = _pkColumns.get(ii); values[ii] = (Comparable<?>)field.getField().get(object); if (values[ii] == null) { nulls++; } else if (values[ii] instanceof Number && ((Number)values[ii]).intValue() == 0) { nulls++; // zeros are considered nulls; see below zeros++; } } // make sure the keys are all null or all non-null if (nulls == 0) { return new Key<T>(_pClass, values); } else if (nulls == values.length) { return null; } else if (nulls == zeros) { // we also allow primary keys where there are zero-valued primitive primary key // columns as along as there is at least one non-zero valued additional key column; // this is a compromise that allows sensible things like (id=99, type=0) but // unfortunately also allows less sensible things like (id=0, type=5) while // continuing to disallow the dangerous (id=0) return new Key<T>(_pClass, values); } // throw an informative error message StringBuilder keys = new StringBuilder(); for (int ii = 0; ii < _pkColumns.size(); ii++) { keys.append(", ").append(_pkColumns.get(ii).getField().getName()); keys.append("=").append(values[ii]); } throw new IllegalArgumentException("Primary key fields are mixed null and non-null " + "[class=" + _pClass.getName() + keys + "]."); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. This is only allowed for records with single column keys. */ public Key<T> makePrimaryKey (Comparable<?> value) { checkHasNonCompositePrimaryKey(); return new Key<T>(_pClass, new Comparable<?>[] { value }); } /** * Creates a Function that changes Comparables into primary keys. */ public Function<Comparable<?>, Key<T>> primaryKeyFunction () { checkHasNonCompositePrimaryKey(); return new Function<Comparable<?>, Key<T>>() { public Key<T> apply (Comparable<?> value) { return new Key<T>(_pClass, new Comparable<?>[] { value }); } }; } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied result set. */ public Key<T> makePrimaryKey (ResultSet rs) throws SQLException { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } Comparable<?>[] values = new Comparable<?>[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { Object keyValue = _pkColumns.get(ii).getFromSet(rs); if (!(keyValue instanceof Comparable<?>)) { throw new IllegalArgumentException("Key field must be Comparable<?> [field=" + _pkColumns.get(ii).getColumnName() + "]"); } values[ii] = (Comparable<?>) keyValue; } return new Key<T>(_pClass, values); } /** * Returns true if this marshaller has been initialized ({@link #init} has been called), its * migrations run and it is ready for operation. False otherwise. */ public boolean isInitialized () { return _meta != null; } /** * Initializes the table used by this marshaller. This is called automatically by the {@link * PersistenceContext} the first time an entity is used. If the table does not exist, it will * be created. If the schema version specified by the persistent object is newer than the * database schema, it will be migrated. */ public void init (PersistenceContext ctx, DepotMetaData meta) throws DatabaseException { if (_meta != null) { // sanity check throw new IllegalStateException( "Cannot re-initialize marshaller [type=" + _pClass + "]."); } _meta = meta; final SQLBuilder builder = ctx.getSQLBuilder(new DepotTypes(ctx, _pClass)); // perform the context-sensitive initialization of the field marshallers for (FieldMarshaller<?> fm : _fields.values()) { fm.init(builder); } // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new ColumnExp[_allFields.length]; ColumnDefinition[] declarations = new ColumnDefinition[_allFields.length]; int jj = 0; for (ColumnExp field : _allFields) { FieldMarshaller<?> fm = _fields.get(field.name); // include all persistent non-computed fields ColumnDefinition colDef = fm.getColumnDefinition(); if (colDef != null) { _columnFields[jj] = field; declarations[jj] = colDef; jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); declarations = ArrayUtil.splice(declarations, jj); // determine whether or not this record has ever been seen int currentVersion = _meta.getVersion(getTableName(), false); if (currentVersion == -1) { log.info("Creating initial version record for " + _pClass.getName() + "."); // if not, create a version entry with version zero _meta.initializeVersion(getTableName()); } // now check whether we need to migrate our database schema while (true) { if (currentVersion >= _schemaVersion) { // TODO: we used to check for staleness here, but that's slow; currently we do it // only after migration, we should reinstate a check maybe the first time a table // is read or something so that developers are more likely to get the warning return; } // try to update migratingVersion to the new version to indicate to other processes // that we are handling the migration and that they should wait if (_meta.updateMigratingVersion(getTableName(), _schemaVersion, 0)) { break; // we got the lock, let's go } // we didn't get the lock, so wait 5 seconds and then check to see if the other process // finished the update or failed in which case we'll try to grab the lock ourselves try { log.info("Waiting on migration lock for " + _pClass.getName() + "."); Thread.sleep(5000); } catch (InterruptedException ie) { throw new DatabaseException("Interrupted while waiting on migration lock."); } currentVersion = _meta.getVersion(getTableName(), true); } // fetch all relevant information regarding our table from the database TableMetaData metaData = TableMetaData.load(ctx, getTableName()); try { if (!metaData.tableExists) { // if the table does not exist, create it createTable(ctx, builder, declarations); metaData = TableMetaData.load(ctx, getTableName()); } else { // if it does exist, run our migrations metaData = runMigrations(ctx, metaData, builder, currentVersion); } // check for stale columns now that the table is up to date checkForStaleness(metaData, ctx, builder); // and update our version in the schema version table _meta.updateVersion(getTableName(), _schemaVersion); } finally { // set our migrating version back to zero try { if (!_meta.updateMigratingVersion(getTableName(), 0, _schemaVersion)) { log.warning("Failed to restore migrating version to zero!", "record", _pClass); } } catch (Exception e) { log.warning("Failure restoring migrating version! Bad bad!", "record", _pClass, e); } } } /** * This is called by the persistence context to register a migration for the entity managed by * this marshaller. */ public void registerMigration (SchemaMigration migration) { _schemaMigs.add(migration); } /** * Creates a persistent object from the supplied result set. The result set must have come from * a properly constructed query (see {@link BuildVisitor}). */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = Sets.newHashSet(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pClass.newInstance(); for (FieldMarshaller<?> fm : _fields.values()) { if (!fields.contains(fm.getColumnName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException( "ResultSet missing field: " + fm.getField().getName() + " for " + _pClass); } fm.getAndWriteToObject(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [class=" + _pClass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Go through the registered {@link ValueGenerator}s for our persistent object and run the ones * that match the current postFactum phase, filling in the fields on the supplied object while * we go. * * The return value is only non-empty for the !postFactum phase, in which case it is a set of * field names that are associated with {@link IdentityValueGenerator}, because these need * special handling in the INSERT (specifically, 'DEFAULT' must be supplied as a value in the * eventual SQL). */ public Set<String> generateFieldValues ( Connection conn, DatabaseLiaison liaison, Object po, boolean postFactum) { Set<String> idFields = Sets.newHashSet(); for (ValueGenerator vg : _valueGenerators.values()) { if (!postFactum && vg instanceof IdentityValueGenerator) { idFields.add(vg.getFieldMarshaller().getField().getName()); } if (vg.isPostFactum() != postFactum) { continue; } try { int nextValue = vg.nextGeneratedValue(conn, liaison); vg.getFieldMarshaller().getField().set(po, nextValue); } catch (Exception e) { throw new IllegalStateException( "Failed to assign primary key [type=" + _pClass + "]", e); } } return idFields; } protected void createTable (PersistenceContext ctx, final SQLBuilder builder, final ColumnDefinition[] declarations) throws DatabaseException { log.info("Creating initial table '" + getTableName() + "'."); ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { // create the table String[] primaryKeyColumns = null; if (_pkColumns != null) { primaryKeyColumns = new String[_pkColumns.size()]; for (int ii = 0; ii < primaryKeyColumns.length; ii ++) { primaryKeyColumns[ii] = _pkColumns.get(ii).getColumnName(); } } liaison.createTableIfMissing(conn, getTableName(), fieldsToColumns(_columnFields), declarations, null, primaryKeyColumns); // add its indexen for (CreateIndexClause iclause : _indexes) { execute(conn, builder, iclause); } // create our value generators for (ValueGenerator vg : _valueGenerators.values()) { vg.create(conn, liaison); } // and its full text search indexes for (FullTextIndex fti : _fullTextIndexes.values()) { builder.addFullTextSearch(conn, DepotMarshaller.this, fti); } return 0; } }); } protected int execute (Connection conn, SQLBuilder builder, QueryClause clause) throws SQLException { if (builder.newQuery(clause)) { return builder.prepare(conn).executeUpdate(); } return 0; } protected TableMetaData runMigrations (final PersistenceContext ctx, TableMetaData metaData, final SQLBuilder builder, int currentVersion) throws DatabaseException { log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); if (_schemaMigs.size() > 0) { // run our pre-default-migrations for (SchemaMigration migration : _schemaMigs) { if (migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // we don't know what the pre-migrations did so we have to re-read metadata metaData = TableMetaData.load(ctx, getTableName()); } // figure out which columns we have in the table now, so that when all is said and done we // can see what new columns we have in the table and run the creation code for any value // generators that are defined on those columns (we can't just track the columns we add in // our automatic migrations because someone might register custom migrations that add // columns specially) Set<String> preMigrateColumns = Sets.newHashSet(metaData.tableColumns); // add any missing columns for (ColumnExp field : _columnFields) { final FieldMarshaller<?> fmarsh = _fields.get(field.name); if (metaData.tableColumns.remove(fmarsh.getColumnName())) { continue; } // otherwise add the column final ColumnDefinition coldef = fmarsh.getColumnDefinition(); log.info("Adding column to " + getTableName() + ": " + fmarsh.getColumnName()); ctx.invoke(new Modifier.Simple() { @Override protected String createQuery (DatabaseLiaison liaison) { return "alter table " + liaison.tableSQL(getTableName()) + " add column " + liaison.columnSQL(fmarsh.getColumnName()) + " " + liaison.expandDefinition(coldef); } }); // if the column is a TIMESTAMP or DATETIME column, we need to run a special query to // update all existing rows to the current time because MySQL annoyingly assigns // TIMESTAMP columns a value of "0000-00-00 00:00:00" regardless of whether we // explicitly provide a "DEFAULT" value for the column or not, and DATETIME columns // cannot accept CURRENT_TIME or NOW() defaults at all. if (!coldef.nullable && coldef.defaultValue == null && (coldef.type.equalsIgnoreCase("timestamp") || coldef.type.equalsIgnoreCase("datetime"))) { log.info("Assigning current time to " + fmarsh.getColumnName() + "."); ctx.invoke(new Modifier.Simple() { @Override protected String createQuery (DatabaseLiaison liaison) { // TODO: is NOW() standard SQL? return "update " + liaison.tableSQL(getTableName()) + " set " + liaison.columnSQL(fmarsh.getColumnName()) + " = NOW()"; } }); } } // if the primary key has changed size or signature, we have to drop and readd it boolean keyMatch; if (metaData.pkColumns.size() == _pkColumns.size()) { keyMatch = true; for (FieldMarshaller<?> column : _pkColumns) { keyMatch &= metaData.pkColumns.contains(column.getField().getName()); } } else { keyMatch = false; } if (!keyMatch) { log.info("Primary key has changed: dropping."); ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { // TODO return 0; } }); } // add or remove the primary key as needed if (hasPrimaryKey() && metaData.pkName == null) { log.info("Adding primary key."); ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.addPrimaryKey( conn, getTableName(), fieldsToColumns(getPrimaryKeyFields())); return 0; } }); } else if (!hasPrimaryKey() && metaData.pkName != null) { final String pkName = metaData.pkName; log.info("Dropping primary key: " + pkName); ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { liaison.dropPrimaryKey(conn, getTableName(), pkName); return 0; } }); } // add any named indices that exist on the record but not yet on the table for (final CreateIndexClause iclause : _indexes) { if (metaData.indexColumns.containsKey(iclause.getName())) { metaData.indexColumns.remove(iclause.getName()); // this index already exists continue; } // but this is a new, named index, so we create it log.info("Creating new index: " + iclause.getName()); ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { execute(conn, builder, iclause); return 0; } }); } // next we create any full text search indexes that exist on the record but not in the // table, first step being to do a dialect-sensitive enumeration of existing indexes Set<String> tableFts = Sets.newHashSet(); builder.getFtsIndexes(metaData.tableColumns, metaData.indexColumns.keySet(), tableFts); // then iterate over what should be there for (final FullTextIndex recordFts : _fullTextIndexes.values()) { if (tableFts.contains(recordFts.name())) { // the table already contains this one continue; } // but not this one, so let's create it ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { builder.addFullTextSearch(conn, DepotMarshaller.this, recordFts); return 0; } }); } // we do not auto-remove columns but rather require that SchemaMigration.Drop records be // registered by hand to avoid accidentally causing the loss of data // we don't auto-remove indices either because we'd have to sort out the potentially // complex origins of an index (which might be because of a @Unique column or maybe the // index was hand defined in a @Column clause) // run our post-default-migrations for (SchemaMigration migration : _schemaMigs) { if (!migration.runBeforeDefault() && migration.shouldRunMigration(currentVersion, _schemaVersion)) { migration.init(getTableName(), _fields); ctx.invoke(migration); } } // now reload our table metadata so that we can see what columns we have now metaData = TableMetaData.load(ctx, getTableName()); // initialize value generators for any columns that have been newly added for (String column : metaData.tableColumns) { if (preMigrateColumns.contains(column)) { continue; } // see if we have a value generator for this new column final ValueGenerator valgen = _valueGenerators.get(column); if (valgen == null) { continue; } // note: if someone renames a column that has an identity value generator, things will // break because Postgres automatically creates a table_column_seq sequence that is // used to generate values for that column and god knows what happens when that is // renamed; plus we're potentially going to try to reinitialize it if it has a non-zero // initialValue which will use the new column name to obtain the sequence name which // ain't going to work either; we punt! ctx.invoke(new Modifier() { @Override protected int invoke (Connection conn, DatabaseLiaison liaison) throws SQLException { valgen.create(conn, liaison); return 0; } }); } return metaData; } protected CreateIndexClause buildIndex (String name, boolean unique) { Method method; try { method = _pClass.getMethod(name); } catch (NoSuchMethodException nsme) { throw new IllegalArgumentException( "Index flagged as complex, but no defining method '" + name + "' found.", nsme); } try { return buildIndex(name, unique, method.invoke(null)); } catch (Exception e) { throw new IllegalArgumentException( "Error calling index definition method '" + name + "'", e); } } protected CreateIndexClause buildIndex (String name, boolean unique, Object config) { List<Tuple<SQLExpression, Order>> definition = Lists.newArrayList(); if (config instanceof ColumnExp) { definition.add(new Tuple<SQLExpression, Order>((ColumnExp)config, Order.ASC)); } else if (config instanceof ColumnExp[]) { for (ColumnExp column : (ColumnExp[])config) { definition.add(new Tuple<SQLExpression, Order>(column, Order.ASC)); } } else if (config instanceof SQLExpression) { definition.add(new Tuple<SQLExpression, Order>((SQLExpression)config, Order.ASC)); } else if (config instanceof Tuple<?,?>) { @SuppressWarnings("unchecked") Tuple<SQLExpression, Order> tuple = (Tuple<SQLExpression, Order>)config; definition.add(tuple); } else if (config instanceof List<?>) { @SuppressWarnings("unchecked") List<Tuple<SQLExpression, Order>> defs = (List<Tuple<SQLExpression, Order>>)config; definition.addAll(defs); } else { throw new IllegalArgumentException( "Method '" + name + "' must return ColumnExp[], SQLExpression or " + "List<Tuple<SQLExpression, Order>>"); } return new CreateIndexClause(_pClass, getTableName() + "_" + name, unique, definition); } // translate an array of field names to an array of column names protected String[] fieldsToColumns (ColumnExp[] fields) { String[] columns = new String[fields.length]; for (int ii = 0; ii < columns.length; ii ++) { FieldMarshaller<?> fm = _fields.get(fields[ii].name); if (fm == null) { throw new IllegalArgumentException( "Unknown field on record [field=" + fields[ii] + ", class=" + _pClass + "]"); } columns[ii] = fm.getColumnName(); } return columns; } /** * Checks that there are no database columns for which we no longer have Java fields. */ protected void checkForStaleness ( TableMetaData meta, PersistenceContext ctx, SQLBuilder builder) throws DatabaseException { for (ColumnExp field : _columnFields) { FieldMarshaller<?> fmarsh = _fields.get(field.name); meta.tableColumns.remove(fmarsh.getColumnName()); } for (String column : meta.tableColumns) { if (builder.isPrivateColumn(column)) { continue; } log.warning(getTableName() + " contains stale column '" + column + "'."); } } protected void checkHasPrimaryKey () { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } } protected void checkHasNonCompositePrimaryKey () { if (_pkColumns == null || _pkColumns.size() != 1) { throw new UnsupportedOperationException( getClass().getName() + " does not define a single column primary key"); } } protected static class TableMetaData { public boolean tableExists; public Set<String> tableColumns = Sets.newHashSet(); public Map<String, Set<String>> indexColumns = Maps.newHashMap(); public String pkName; public Set<String> pkColumns = Sets.newHashSet(); public static TableMetaData load (PersistenceContext ctx, final String tableName) throws DatabaseException { return ctx.invoke(new Query.Trivial<TableMetaData>() { public TableMetaData invoke (PersistenceContext ctx, Connection conn, DatabaseLiaison dl) throws SQLException { return new TableMetaData(conn.getMetaData(), tableName); } public void updateStats (Stats stats) { // nothing doing } }); } public TableMetaData (DatabaseMetaData meta, String tableName) throws SQLException { tableExists = meta.getTables(null, null, tableName, null).next(); if (!tableExists) { return; } ResultSet rs = meta.getColumns(null, null, tableName, "%"); while (rs.next()) { tableColumns.add(rs.getString("COLUMN_NAME")); } rs = meta.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String indexName = rs.getString("INDEX_NAME"); Set<String> set = indexColumns.get(indexName); if (rs.getBoolean("NON_UNIQUE")) { // not a unique index: just make sure there's an entry in the keyset if (set == null) { indexColumns.put(indexName, null); } } else { // for unique indices we collect the column names if (set == null) { set = Sets.newHashSet(); indexColumns.put(indexName, set); } set.add(rs.getString("COLUMN_NAME")); } } rs = meta.getPrimaryKeys(null, null, tableName); while (rs.next()) { pkName = rs.getString("PK_NAME"); pkColumns.add(rs.getString("COLUMN_NAME")); } } @Override public String toString () { return StringUtil.fieldsToString(this); } } /** Provides access to certain internal metadata. */ protected DepotMetaData _meta; /** The persistent object class that we manage. */ protected Class<T> _pClass; /** The name of our persistent object table. */ protected String _tableName; /** The @Computed annotation of this entity, or null. */ protected Computed _computed; /** A mapping of field names to value generators for that field. */ protected Map<String, ValueGenerator> _valueGenerators = Maps.newHashMap(); /** A field marshaller for each persistent field in our object. */ protected Map<String, FieldMarshaller<?>> _fields = Maps.newHashMap(); /** The field marshallers for our persistent object's primary key columns or null if it did not * define a primary key. */ protected List<FieldMarshaller<?>> _pkColumns; /** The persisent fields of our object, in definition order. */ protected ColumnExp[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected ColumnExp[] _columnFields; /** The indexes defined for this record. */ protected List<CreateIndexClause> _indexes = Lists.newArrayList(); /** Any full text indices defined on this entity. */ protected Map<String, FullTextIndex> _fullTextIndexes = Maps.newHashMap(); /** The version of our persistent object schema as specified in the class definition. */ protected int _schemaVersion = -1; /** A list of hand registered schema migrations to run prior to doing the default migration. */ protected List<SchemaMigration> _schemaMigs = Lists.newArrayList(); }
package com.vaadin.ui; import com.vaadin.server.Resource; import com.vaadin.shared.ui.AbstractEmbeddedState; /** * Abstract base for embedding components. * * @author Vaadin Ltd. * @version * @VERSION@ * @since 7.0 */ @SuppressWarnings("serial") public abstract class AbstractEmbedded extends AbstractComponent { @Override protected AbstractEmbeddedState getState() { return (AbstractEmbeddedState) super.getState(); } /** * Sets the object source resource. The dimensions are assumed if possible. * The type is guessed from resource. * * @param source * the source to set. */ public void setSource(Resource source) { setResource(AbstractEmbeddedState.SOURCE_RESOURCE, source); } /** * Get the object source resource. * * @return the source */ public Resource getSource() { return getResource(AbstractEmbeddedState.SOURCE_RESOURCE); } /** * Sets this component's alternate text that can be presented instead of the * component's normal content for accessibility purposes. * * @param altText * A short, human-readable description of this component's * content. */ public void setAlternateText(String altText) { getState().alternateText = altText; } /** * Gets this component's alternate text that can be presented instead of the * component's normal content for accessibility purposes. * * @returns Alternate text */ public String getAlternateText() { return getState().alternateText; } }
package mockit.multicore; import java.io.*; import java.net.*; import java.util.*; import mockit.internal.*; final class CopyingClassLoader extends ClassLoader { private static final ClassLoader SYSTEM_CL = ClassLoader.getSystemClassLoader(); CopyingClassLoader() { super(SYSTEM_CL.getParent()); } Class<?> getCopy(String className) { return findClass(className); } @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if ( name.startsWith("org.junit.") || name.startsWith("junit.framework.") || name.startsWith("mockit.") && !name.startsWith("mockit.integration.logging.") ) { Class<?> theClass = SYSTEM_CL.loadClass(name); if (resolve) { resolveClass(theClass); } return theClass; } return super.loadClass(name, resolve); } @Override protected Class<?> findClass(String name) { Class<?> loadedClass = findLoadedClass(name); if (loadedClass != null) { return loadedClass; } definePackageForCopiedClass(name); byte[] classBytecode = ClassFile.createClassFileReader(name).b; return defineClass(name, classBytecode, 0, classBytecode.length); } private void definePackageForCopiedClass(String name) { int p = name.lastIndexOf('.'); if (p > 0) { String packageName = name.substring(0, p); if (getPackage(packageName) == null) { definePackage(packageName, null, null, null, null, null, null, null); } } } boolean hasLoadedClass(Class<?> aClass) { return findLoadedClass(aClass.getName()) != null; } @Override protected URL findResource(String name) { URL resource; // Somehow, getResource returns null sometimes, but retrying eventually works. do { resource = SYSTEM_CL.getResource(name); } while (resource == null); return resource; } @Override protected Enumeration<URL> findResources(String name) throws IOException { return SYSTEM_CL.getResources(name); } }
// samskivert library - useful routines for java programs // 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.samskivert.jdbc.depot; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import com.samskivert.jdbc.depot.annotation.Computed; import com.samskivert.jdbc.depot.annotation.GeneratedValue; import com.samskivert.jdbc.depot.annotation.Id; import com.samskivert.jdbc.depot.annotation.TableGenerator; import com.samskivert.jdbc.depot.annotation.Transient; import com.samskivert.jdbc.JDBCUtil; import com.samskivert.jdbc.depot.clause.Where; import com.samskivert.jdbc.depot.expression.ColumnExp; import com.samskivert.util.ArrayUtil; import com.samskivert.util.ListUtil; import com.samskivert.util.StringUtil; import static com.samskivert.jdbc.depot.Log.log; /** * Handles the marshalling and unmarshalling of persistent instances to JDBC primitives ({@link * PreparedStatement} and {@link ResultSet}). */ public class DepotMarshaller<T> { /** The name of a private static field that must be defined for all persistent object classes. * It is used to handle schema migration. If automatic schema migration is not desired, define * this field and set its value to -1. */ public static final String SCHEMA_VERSION_FIELD = "SCHEMA_VERSION"; /** * Creates a marshaller for the specified persistent object class. */ public DepotMarshaller (Class<T> pclass, PersistenceContext context) { _pclass = pclass; // see if this is a computed entity Computed computed = pclass.getAnnotation(Computed.class); if (computed == null) { // if not, this class has a corresponding SQL table _tableName = _pclass.getName(); _tableName = _tableName.substring(_tableName.lastIndexOf(".")+1); } // if the entity defines a new TableGenerator, map that in our static table as those are // shared across all entities TableGenerator generator = pclass.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } // introspect on the class and create marshallers for persistent fields ArrayList<String> fields = new ArrayList<String>(); for (Field field : _pclass.getFields()) { int mods = field.getModifiers(); // check for a static constant schema version if ((mods & Modifier.STATIC) != 0 && field.getName().equals(SCHEMA_VERSION_FIELD)) { try { _schemaVersion = (Integer)field.get(null); } catch (Exception e) { log.log(Level.WARNING, "Failed to read schema version " + "[class=" + _pclass + "].", e); } } // the field must be public, non-static and non-transient if (((mods & Modifier.PUBLIC) == 0) || ((mods & Modifier.STATIC) != 0) || field.getAnnotation(Transient.class) != null) { continue; } FieldMarshaller fm = FieldMarshaller.createMarshaller(field); _fields.put(fm.getColumnName(), fm); fields.add(fm.getColumnName()); // check to see if this is our primary key if (field.getAnnotation(Id.class) != null) { if (_pkColumns == null) { _pkColumns = new ArrayList<FieldMarshaller>(); } _pkColumns.add(fm); // check if this field defines a new TableGenerator generator = field.getAnnotation(TableGenerator.class); if (generator != null) { context.tableGenerators.put(generator.name(), generator); } } } // if the entity defines a single-columnar primary key, figure out if we will be generating // values for it if (_pkColumns != null) { GeneratedValue gv = null; FieldMarshaller keyField = null; // loop over fields to see if there's a @GeneratedValue at all for (FieldMarshaller field : _pkColumns) { gv = field.getGeneratedValue(); if (gv != null) { keyField = field; break; } } if (keyField != null) { // and if there is, make sure we've a single-column id if (_pkColumns.size() > 1) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on multiple-column @Id's"); } // the primary key must be numeric if we are to auto-assign it Class<?> ftype = keyField.getField().getType(); boolean isNumeric = ( ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE) || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class) || ftype.equals(Long.TYPE) || ftype.equals(Long.class)); if (!isNumeric) { throw new IllegalArgumentException( "Cannot use @GeneratedValue on non-numeric column"); } switch(gv.strategy()) { case AUTO: case IDENTITY: _keyGenerator = new IdentityKeyGenerator(); break; case TABLE: String name = gv.generator(); generator = context.tableGenerators.get(name); if (generator == null) { throw new IllegalArgumentException( "Unknown generator [generator=" + name + "]"); } _keyGenerator = new TableKeyGenerator(generator); break; } } } // generate our full list of fields/columns for use in queries _allFields = fields.toArray(new String[fields.size()]); // if we're a computed entity, stop here if (_tableName == null) { return; } // figure out the list of fields that correspond to actual table columns and generate the // SQL used to create and migrate our table (unless we're a computed entity) _columnFields = new String[_allFields.length]; _columnDefinitions = new String[_allFields.length]; int jj = 0; for (int ii = 0; ii < _allFields.length; ii++) { // include all persistent non-computed fields String colDef = _fields.get(_allFields[ii]).getColumnDefinition(); if (colDef != null) { _columnFields[jj] = _allFields[ii]; _columnDefinitions[jj] = colDef; jj ++; } } _columnFields = ArrayUtil.splice(_columnFields, jj); _columnDefinitions = ArrayUtil.splice(_columnDefinitions, jj); // add the primary key, if we have one if (hasPrimaryKey()) { String[] indices = new String[_pkColumns.size()]; for (int ii = 0; ii < indices.length; ii ++) { indices[ii] = _pkColumns.get(ii).getColumnName(); } _columnDefinitions = ArrayUtil.append( _columnDefinitions, "PRIMARY KEY (" + StringUtil.join(indices, ", ") + ")"); } _postamble = ""; // TODO: add annotations for the postamble // if we did not find a schema version field, complain if (_schemaVersion < 0) { log.warning("Unable to read " + _pclass.getName() + "." + SCHEMA_VERSION_FIELD + ". Schema migration disabled."); } } /** * Returns the name of the table in which persistence instances of this class are stored. By * default this is the classname of the persistent object without the package. */ public String getTableName () { return _tableName; } /** * Returns true if our persistent object defines a primary key. */ public boolean hasPrimaryKey () { return (_pkColumns != null); } /** * Returns a key configured with the primary key of the supplied object. Throws an exception * if the persistent object did not declare a primary key. */ public Key getPrimaryKey (Object object) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } try { Comparable[] values = new Comparable[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); values[ii] = (Comparable) field.getField().get(object); } return makePrimaryKey(values); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } /** * Creates a primary key record for the type of object handled by this marshaller, using the * supplied primary key value. */ public Key makePrimaryKey (Comparable... values) { if (!hasPrimaryKey()) { throw new UnsupportedOperationException( getClass().getName() + " does not define a primary key"); } if (values.length != _pkColumns.size()) { throw new IllegalArgumentException( "Argument count (" + values.length + ") must match primary key size (" + _pkColumns.size() + ")"); } ColumnExp[] columns = new ColumnExp[_pkColumns.size()]; for (int ii = 0; ii < _pkColumns.size(); ii++) { FieldMarshaller field = _pkColumns.get(ii); columns[ii] = new ColumnExp(_pclass, field.getColumnName()); } return new Key(columns, values); } /** * Initializes the table used by this marshaller. If the table does not exist, it will be * created. If the schema version specified by the persistent object is newer than the database * schema, it will be migrated. */ public void init (Connection conn) throws SQLException { // if we have no table (i.e. we're a computed entity), we have nothing to create if (getTableName() == null) { return; } // check to see if our schema version table exists, create it if not JDBCUtil.createTableIfMissing(conn, SCHEMA_VERSION_TABLE, new String[] { "persistentClass VARCHAR(255) NOT NULL", "version INTEGER NOT NULL" }, ""); // now create the table for our persistent class if it does not exist if (!JDBCUtil.tableExists(conn, getTableName())) { log.fine("Creating table " + getTableName() + " (" + StringUtil.join(_columnDefinitions, ", ") + ") " + _postamble); JDBCUtil.createTableIfMissing(conn, getTableName(), _columnDefinitions, _postamble); updateVersion(conn, 1); } // if we have a key generator, initialize that too if (_keyGenerator != null) { _keyGenerator.init(conn); } // if schema versioning is disabled, stop now if (_schemaVersion < 0) { return; } // make sure the versions match int currentVersion = readVersion(conn); if (currentVersion == _schemaVersion) { return; } log.info("Migrating " + getTableName() + " from " + currentVersion + " to " + _schemaVersion + "..."); // otherwise try to migrate the schema; doing column additions magically and running any // registered hand-migrations DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getColumns(null, null, getTableName(), "%"); HashSet<String> columns = new HashSet<String>(); while (rs.next()) { columns.add(rs.getString("COLUMN_NAME")); } for (String fname : _columnFields) { FieldMarshaller fmarsh = _fields.get(fname); if (columns.contains(fmarsh.getColumnName())) { continue; } // otherwise add the column String coldef = fmarsh.getColumnDefinition(); String query = "alter table " + getTableName() + " add column " + coldef; // try to add it to the appropriate spot int fidx = ListUtil.indexOf(_allFields, fmarsh.getColumnName()); if (fidx == 0) { query += " first"; } else { query += " after " + _allFields[fidx-1]; } log.info("Adding column to " + getTableName() + ": " + coldef); Statement stmt = conn.createStatement(); try { stmt.executeUpdate(query); } finally { stmt.close(); } // if the column is a TIMESTAMP column, we need to run a special query to update all // existing rows to the current time because MySQL annoyingly assigns them a default // value of "0000-00-00 00:00:00" regardless of whether we explicitly provide a // "DEFAULT" value for the column or not if (coldef.toLowerCase().indexOf(" timestamp") != -1) { query = "update " + getTableName() + " set " + fmarsh.getColumnName() + " = NOW()"; log.info("Assigning current time to TIMESTAMP column: " + query); stmt = conn.createStatement(); try { stmt.executeUpdate(query); } finally { stmt.close(); } } } // TODO: run any registered hand migrations updateVersion(conn, _schemaVersion); } /** * Creates a persistent object from the supplied result set. The result set must have come from * a query provided by {@link #createQuery}. */ public T createObject (ResultSet rs) throws SQLException { try { // first, build a set of the fields that we actually received Set<String> fields = new HashSet<String>(); ResultSetMetaData metadata = rs.getMetaData(); for (int ii = 1; ii <= metadata.getColumnCount(); ii ++) { fields.add(metadata.getColumnName(ii)); } // then create and populate the persistent object T po = _pclass.newInstance(); for (FieldMarshaller fm : _fields.values()) { if (!fields.contains(fm.getField().getName())) { // this field was not in the result set, make sure that's OK if (fm.getComputed() != null && !fm.getComputed().required()) { continue; } throw new SQLException("ResultSet missing field: " + fm.getField().getName()); } fm.getValue(rs, po); } return po; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to unmarshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will insert the supplied persistent object into the database. */ public PreparedStatement createInsert (Connection conn, Object po) throws SQLException { requireNotComputed("insert rows into"); try { StringBuilder insert = new StringBuilder(); insert.append("insert into ").append(getTableName()); insert.append(" (").append(StringUtil.join(_columnFields, ",")); insert.append(")").append(" values("); for (int ii = 0; ii < _columnFields.length; ii++) { if (ii > 0) { insert.append(", "); } insert.append("?"); } insert.append(")"); // TODO: handle primary key, nullable fields specially? PreparedStatement pstmt = conn.prepareStatement(insert.toString()); int idx = 0; for (String field : _columnFields) { _fields.get(field).setValue(po, pstmt, ++idx); } return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object [pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Fills in the primary key just assigned to the supplied persistence object by the execution * of the results of {@link #createInsert}. * * @return the newly assigned primary key or null if the object does not use primary keys or * this is not the right time to assign the key. */ public Key assignPrimaryKey (Connection conn, Object po, boolean postFactum) throws SQLException { // if we have no primary key or no generator, then we're done if (!hasPrimaryKey() || _keyGenerator == null) { return null; } // run this generator either before or after the actual insertion if (_keyGenerator.isPostFactum() != postFactum) { return null; } try { int nextValue = _keyGenerator.nextGeneratedValue(conn); _pkColumns.get(0).getField().set(po, nextValue); return makePrimaryKey(nextValue); } catch (Exception e) { String errmsg = "Failed to assign primary key [type=" + _pclass + "]"; throw (SQLException) new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the supplied persistent object using the supplied key. */ public PreparedStatement createUpdate (Connection conn, Object po, Where key) throws SQLException { return createUpdate(conn, po, key, _columnFields); } /** * Creates a statement that will update the supplied persistent object * using the supplied key. */ public PreparedStatement createUpdate ( Connection conn, Object po, Where key, String[] modifiedFields) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); try { PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (String field : modifiedFields) { _fields.get(field).setValue(po, pstmt, ++idx); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } catch (SQLException sqe) { // pass this on through throw sqe; } catch (Exception e) { String errmsg = "Failed to marshall persistent object " + "[pclass=" + _pclass.getName() + "]"; throw (SQLException)new SQLException(errmsg).initCause(e); } } /** * Creates a statement that will update the specified set of fields for all persistent objects * that match the supplied key. */ public PreparedStatement createPartialUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); int idx = 0; for (String field : modifiedFields) { if (idx++ > 0) { update.append(", "); } update.append(field).append(" = ?"); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); idx = 0; // bind the update arguments for (Object value : modifiedValues) { // TODO: use the field marshaller? pstmt.setObject(++idx, value); } // now bind the key arguments key.bindArguments(pstmt, ++idx); return pstmt; } /** * Creates a statement that will delete all rows matching the supplied key. */ public PreparedStatement createDelete (Connection conn, Where key) throws SQLException { requireNotComputed("delete rows from"); StringBuilder query = new StringBuilder("delete from " + getTableName()); key.appendClause(null, query); PreparedStatement pstmt = conn.prepareStatement(query.toString()); key.bindArguments(pstmt, 1); return pstmt; } /** * Creates a statement that will update the specified set of fields, using the supplied literal * SQL values, for all persistent objects that match the supplied key. */ public PreparedStatement createLiteralUpdate ( Connection conn, Where key, String[] modifiedFields, Object[] modifiedValues) throws SQLException { requireNotComputed("update rows in"); StringBuilder update = new StringBuilder(); update.append("update ").append(getTableName()).append(" set "); for (int ii = 0; ii < modifiedFields.length; ii++) { if (ii > 0) { update.append(", "); } update.append(modifiedFields[ii]).append(" = "); update.append(modifiedValues[ii]); } key.appendClause(null, update); PreparedStatement pstmt = conn.prepareStatement(update.toString()); key.bindArguments(pstmt, 1); return pstmt; } protected void updateVersion (Connection conn, int version) throws SQLException { String update = "update " + SCHEMA_VERSION_TABLE + " set version = " + version + " where persistentClass = '" + getTableName() + "'"; String insert = "insert into " + SCHEMA_VERSION_TABLE + " values('" + getTableName() + "', " + version + ")"; Statement stmt = conn.createStatement(); try { if (stmt.executeUpdate(update) == 0) { stmt.executeUpdate(insert); } } finally { stmt.close(); } } protected int readVersion (Connection conn) throws SQLException { String query = "select version from " + SCHEMA_VERSION_TABLE + " where persistentClass = '" + getTableName() + "'"; Statement stmt = conn.createStatement(); try { ResultSet rs = stmt.executeQuery(query); return (rs.next()) ? rs.getInt(1) : 1; } finally { stmt.close(); } } protected void requireNotComputed (String action) throws SQLException { if (getTableName() == null) { throw new IllegalArgumentException( "Can't " + action + " computed entities [class=" + _pclass + "]"); } } /** The persistent object class that we manage. */ protected Class<T> _pclass; /** The name of our persistent object table. */ protected String _tableName; /** A field marshaller for each persistent field in our object. */ protected HashMap<String, FieldMarshaller> _fields = new HashMap<String, FieldMarshaller>(); /** The field marshallers for our persistent object's primary key columns * or null if it did not define a primary key. */ protected ArrayList<FieldMarshaller> _pkColumns; /** The generator to use for auto-generating primary key values, or null. */ protected KeyGenerator _keyGenerator; /** The persisent fields of our object, in definition order. */ protected String[] _allFields; /** The fields of our object with directly corresponding table columns. */ protected String[] _columnFields; /** The version of our persistent object schema as specified in the class * definition. */ protected int _schemaVersion = -1; /** Used when creating and migrating our table schema. */ protected String[] _columnDefinitions; /** Used when creating and migrating our table schema. */ protected String _postamble; /** The name of the table we use to track schema versions. */ protected static final String SCHEMA_VERSION_TABLE = "DepotSchemaVersion"; }
// $Id: PlaceRegistry.java,v 1.6 2001/08/11 04:03:25 mdb Exp $ package com.threerings.cocktail.party.server; import java.util.Enumeration; import java.util.Properties; import com.samskivert.util.Config; import com.samskivert.util.Queue; import com.threerings.cocktail.cher.dobj.*; import com.threerings.cocktail.cher.util.IntMap; import com.threerings.cocktail.party.Log; import com.threerings.cocktail.party.data.PlaceObject; /** * The place registry keeps track of all of the active places in the * server. It should be used to create new places and it will take care of * instantiating and initializing a place manager to manage newly created * places. */ public class PlaceRegistry implements Subscriber { /** * Creates and initializes the place registry; called by the server * during its initialization phase. */ public PlaceRegistry (Config config) { } /** * Creates and registers a new place along with a manager to manage * that place. The place object class and place manager class are * determined from the configuration information provided in the * supplied properties instance. * * @param config the configuration information for this place manager. * * @return a reference to the place manager that will manage the new * place object or null if an error occurred creating the place or * place manager. * * @exception InstantiationException thrown if an error occurs trying * to instantiate and initialize the place manager. * * @see PlaceConfig#PLACEOBJ_CLASS * @see PlaceConfig#PLACEMGR_CLASS */ public PlaceManager createPlace (Properties config) throws InstantiationException { String pobjcl = config.getProperty(PlaceConfig.PLACEOBJ_CLASS); if (pobjcl == null) { throw new InstantiationException( "No place object classname specified in place config."); } String pmgrcl = config.getProperty(PlaceConfig.PLACEMGR_CLASS); if (pobjcl == null) { throw new InstantiationException( "No place manager classname specified in place config."); } try { return createPlace(Class.forName(pobjcl), Class.forName(pmgrcl), config); } catch (Exception e) { throw new InstantiationException( "Error instantiating class: " + e); } } /** * Creates and registers a new place along with a manager to manage * that place. The registry takes care of tracking the creation of the * object and informing the manager when it is created. * * @param pobjClass the <code>PlaceObject</code> derived class that * should be instantiated to create the place object. * @param pmgrClass the <code>PlaceManager</code> derived class that * should be instantiated to manage the place. * @param config the configuration information for this place manager. * * @return a reference to the place manager that will manage the new * place object. * * @exception InstantiationException thrown if an error occurs trying * to instantiate and initialize the place manager. */ public PlaceManager createPlace (Class pobjClass, Class pmgrClass, Properties config) throws InstantiationException { try { // create a place manager for this place PlaceManager pmgr = (PlaceManager)pmgrClass.newInstance(); // let the pmgr know about us pmgr.init(this, config); // stick the manager on the creation queue because we know // we'll get our calls to objectAvailable()/requestFailed() in // the order that we call createObject() _createq.append(pmgr); // and request to create the place object PartyServer.omgr.createObject(pobjClass, this, false); return pmgr; } catch (IllegalAccessException iae) { throw new InstantiationException( "Error instantiating place manager: " + iae); } } /** * Returns an enumeration of all of the registered place objects. This * should only be accessed on the dobjmgr thread and shouldn't be kept * around across event dispatches. */ public Enumeration getPlaces () { final Enumeration enum = _pmgrs.elements(); return new Enumeration() { public boolean hasMoreElements () { return enum.hasMoreElements(); } public Object nextElement () { PlaceManager plmgr = (PlaceManager)enum.nextElement(); return (plmgr == null) ? null : plmgr.getPlaceObject(); } }; } /** * Returns an enumeration of all of the registered place managers. * This should only be accessed on the dobjmgr thread and shouldn't be * kept around across event dispatches. */ public Enumeration getPlaceManagers () { return _pmgrs.elements(); } /** * Unregisters the place from the registry. Called by the place * manager when a place object that it was managing is destroyed. */ public void placeWasDestroyed (int oid) { // remove the place manager from the table _pmgrs.remove(oid); } public void objectAvailable (DObject object) { // pop the next place manager off of the queue and let it know // that everything went swimmingly PlaceManager pmgr = (PlaceManager)_createq.getNonBlocking(); if (pmgr == null) { Log.warning("Place created but no manager queued up to hear " + "about it!? [pobj=" + object + "]."); return; } // make sure it's the right kind of object if (!(object instanceof PlaceObject)) { Log.warning("Place registry notified of the creation of " + "non-place object!? [obj=" + object + "]."); return; } // start the place manager up with the newly created place object pmgr.startup((PlaceObject)object); // stick the manager into our table _pmgrs.put(object.getOid(), pmgr); } public void requestFailed (int oid, ObjectAccessException cause) { // pop a place manager off the queue since it is queued up to // manage the failed place object PlaceManager pmgr = (PlaceManager)_createq.getNonBlocking(); if (pmgr == null) { Log.warning("Place creation failed but no manager queued " + "up to hear about it!? [cause=" + cause + "]."); return; } Log.warning("Failed to create place object [mgr=" + pmgr + ", cause=" + cause + "]."); } public boolean handleEvent (DEvent event, DObject target) { // this shouldn't be called because we don't subscribe to // anything, we just want to hear about object creation return false; } protected Queue _createq = new Queue(); protected IntMap _pmgrs = new IntMap(); }
package org.micro.neural; import org.micro.neural.common.URL; import org.micro.neural.config.GlobalConfig; import org.micro.neural.config.GlobalConfig.*; import org.micro.neural.config.RuleConfig; import java.util.Map; /** * The Neural. * * @author lry */ public interface Neural<C extends RuleConfig, G extends GlobalConfig> { /** * The initialize * * @param url {@link URL} */ void initialize(URL url); /** * The get global config * * @return {@link G} */ G getGlobalConfig(); /** * The add degrade * * @param config {@link C} */ void addConfig(C config); /** * The notify of changed config * * @param category {@link Category} * @param identity the config identity, format: [module]:[application]:[group]:[resource] * @param data the config data, format: serialize config data */ void notify(Category category, String identity, String data); /** * The collect of get and reset statistics data * * @return statistics data */ Map<String, Map<String, Long>> collect(); /** * The get statistics data * * @return statistics data */ Map<String, Map<String, Long>> statistics(); /** * The process of wrapper original call * * @param identity {@link org.micro.neural.config.RuleConfig} * @param originalCall {@link OriginalCall} * @return invoke return object * @throws Throwable throw exception */ Object wrapperCall(String identity, OriginalCall originalCall) throws Throwable; /** * The destroy */ void destroy(); }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //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 opennlp.tools.lang.english; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.regex.Pattern; import opennlp.maxent.io.SuffixSensitiveGISModelReader; import opennlp.tools.ngram.Dictionary; import opennlp.tools.parser.Parse; import opennlp.tools.lang.english.ParserChunker; import opennlp.tools.parser.ParserME; import opennlp.tools.lang.english.ParserTagger; import opennlp.tools.util.Span; /** * Class for performing full parsing on English text. */ public class TreebankParser { private static Pattern untokenizedParenPattern1 = Pattern.compile("([^ ])([({)}])"); private static Pattern untokenizedParenPattern2 = Pattern.compile("([({)}])([^ ])"); public static ParserME getParser(String dataDir, boolean useTagDictionary, boolean useCaseSensitiveTagDictionary, int beamSize, double advancePercentage) throws IOException { if (useTagDictionary) { return new ParserME( new SuffixSensitiveGISModelReader(new File(dataDir + "/build.bin.gz")).getModel(), new SuffixSensitiveGISModelReader(new File(dataDir + "/check.bin.gz")).getModel(), new ParserTagger(dataDir + "/tag.bin.gz", dataDir + "/tagdict", useCaseSensitiveTagDictionary ),//, new Dictionary(dataDir+"/dict.bin.gz")), new ParserChunker(dataDir + "/chunk.bin.gz"), new HeadRules(dataDir + "/head_rules"),beamSize,advancePercentage); } else { return new ParserME( new SuffixSensitiveGISModelReader(new File(dataDir + "/build.bin.gz")).getModel(), new SuffixSensitiveGISModelReader(new File(dataDir + "/check.bin.gz")).getModel(), new ParserTagger(dataDir + "/tag.bin.gz", dataDir + "/tagdict", useCaseSensitiveTagDictionary), //new Dictionary(dataDir+"/dict.bin.gz")), new ParserChunker(dataDir + "/chunk.bin.gz"), new HeadRules(dataDir + "/head_rules"),beamSize,advancePercentage); } } public static ParserME getParser(String dataDir) throws IOException { return getParser(dataDir,true,false,ParserME.defaultBeamSize,ParserME.defaultAdvancePercentage); } private static String convertToken(String token) { if (token.equals("(")) { return "-LRB-"; } else if (token.equals(")")) { return "-RRB-"; } else if (token.equals("{")) { return "-LCB-"; } else if (token.equals("}")) { return "-RCB-"; } return token; } public static Parse[] parseLine(String line, ParserME parser, int numParses) { line = untokenizedParenPattern1.matcher(line).replaceAll("$1 $2"); line = untokenizedParenPattern2.matcher(line).replaceAll("$1 $2"); StringTokenizer str = new StringTokenizer(line); StringBuffer sb = new StringBuffer(); List tokens = new ArrayList(); while (str.hasMoreTokens()) { String tok = convertToken(str.nextToken()); tokens.add(tok); sb.append(tok).append(" "); } String text = sb.substring(0, sb.length() - 1).toString(); Parse p = new Parse(text, new Span(0, text.length()), "INC", 1, null); int start = 0; for (Iterator ti = tokens.iterator(); ti.hasNext();) { String tok = (String) ti.next(); p.insert(new Parse(text, new Span(start, start + tok.length()), ParserME.TOK_NODE, 0)); start += tok.length() + 1; } Parse[] parses = parser.parse(p,numParses); return parses; } private static void usage() { System.err.println("Usage: TreebankParser -[id] -bs -ap dataDirectory < tokenized_sentences"); System.err.println("dataDirectory: Directory containing parser models."); System.err.println("-d: Use tag dictionary."); System.err.println("-i: Case insensitive tag dictionary."); System.err.println("-bs 20: Use a beam size of 20."); System.err.println("-ap 0.95: Advance outcomes in with at least 95% of the probability mass."); System.err.println("-k 5: Show the top 5 parses. This will also display their log-probablities."); System.exit(1); } public static void main(String[] args) throws IOException { if (args.length == 0) { usage(); } boolean useTagDictionary = false; boolean caseInsensitiveTagDictionary = false; boolean showTopK = false; int numParses = 1; int ai = 0; int beamSize = ParserME.defaultBeamSize; double advancePercentage = ParserME.defaultAdvancePercentage; while (args[ai].startsWith("-")) { if (args[ai].equals("-d")) { useTagDictionary = true; } else if (args[ai].equals("-i")) { caseInsensitiveTagDictionary = true; } else if (args[ai].equals("-bs")) { if (args.length > ai+1) { try { beamSize=Integer.parseInt(args[ai+1]); ai++; } catch(NumberFormatException nfe) { System.err.println(nfe); usage(); } } else { usage(); } } else if (args[ai].equals("-ap")) { if (args.length > ai+1) { try { advancePercentage=Double.parseDouble(args[ai+1]); ai++; } catch(NumberFormatException nfe) { System.err.println(nfe); usage(); } } else { usage(); } } else if (args[ai].equals("-k")) { showTopK = true; if (args.length > ai+1) { try { numParses=Integer.parseInt(args[ai+1]); ai++; } catch(NumberFormatException nfe) { System.err.println(nfe); usage(); } } else { usage(); } } else if (args[ai].equals(" ai++; break; } ai++; } ParserME parser; if (caseInsensitiveTagDictionary) { parser = TreebankParser.getParser(args[ai++], true, false,beamSize,advancePercentage); } else if (useTagDictionary) { parser = TreebankParser.getParser(args[ai++], true, true,beamSize,advancePercentage); } else { parser = TreebankParser.getParser(args[ai++], false, false,beamSize,advancePercentage); } BufferedReader in; if (ai == args.length) { in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new FileReader(args[ai])); } String line; try { while (null != (line = in.readLine())) { if (line.length() == 0) { System.out.println(); } else { Parse[] parses = parseLine(line, parser, numParses); for (int pi=0,pn=parses.length;pi<pn;pi++) { if (showTopK) { System.out.print(pi+" "+parses[pi].getProb()+" "); } parses[pi].show(); } } } } catch (IOException e) { System.err.println(e); } } }
package com.thoughtworks.xstream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.NotActiveException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.ConverterRegistry; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.basic.BigDecimalConverter; import com.thoughtworks.xstream.converters.basic.BigIntegerConverter; import com.thoughtworks.xstream.converters.basic.BooleanConverter; import com.thoughtworks.xstream.converters.basic.ByteConverter; import com.thoughtworks.xstream.converters.basic.CharConverter; import com.thoughtworks.xstream.converters.basic.DateConverter; import com.thoughtworks.xstream.converters.basic.DoubleConverter; import com.thoughtworks.xstream.converters.basic.FloatConverter; import com.thoughtworks.xstream.converters.basic.IntConverter; import com.thoughtworks.xstream.converters.basic.LongConverter; import com.thoughtworks.xstream.converters.basic.NullConverter; import com.thoughtworks.xstream.converters.basic.ShortConverter; import com.thoughtworks.xstream.converters.basic.StringBufferConverter; import com.thoughtworks.xstream.converters.basic.StringConverter; import com.thoughtworks.xstream.converters.basic.URIConverter; import com.thoughtworks.xstream.converters.basic.URLConverter; import com.thoughtworks.xstream.converters.collections.ArrayConverter; import com.thoughtworks.xstream.converters.collections.BitSetConverter; import com.thoughtworks.xstream.converters.collections.CharArrayConverter; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.converters.collections.MapConverter; import com.thoughtworks.xstream.converters.collections.PropertiesConverter; import com.thoughtworks.xstream.converters.collections.TreeMapConverter; import com.thoughtworks.xstream.converters.collections.TreeSetConverter; import com.thoughtworks.xstream.converters.extended.ColorConverter; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import com.thoughtworks.xstream.converters.extended.FileConverter; import com.thoughtworks.xstream.converters.extended.FontConverter; import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter; import com.thoughtworks.xstream.converters.extended.JavaClassConverter; import com.thoughtworks.xstream.converters.extended.JavaFieldConverter; import com.thoughtworks.xstream.converters.extended.JavaMethodConverter; import com.thoughtworks.xstream.converters.extended.LocaleConverter; import com.thoughtworks.xstream.converters.extended.LookAndFeelConverter; import com.thoughtworks.xstream.converters.extended.SqlDateConverter; import com.thoughtworks.xstream.converters.extended.SqlTimeConverter; import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter; import com.thoughtworks.xstream.converters.extended.TextAttributeConverter; import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker; import com.thoughtworks.xstream.converters.reflection.SerializableConverter; import com.thoughtworks.xstream.core.DefaultConverterLookup; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.MapBackedDataHolder; import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy; import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy; import com.thoughtworks.xstream.core.TreeMarshallingStrategy; import com.thoughtworks.xstream.core.util.ClassLoaderReference; import com.thoughtworks.xstream.core.util.CompositeClassLoader; import com.thoughtworks.xstream.core.util.CustomObjectInputStream; import com.thoughtworks.xstream.core.util.CustomObjectOutputStream; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.StatefulWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.mapper.AnnotationConfiguration; import com.thoughtworks.xstream.mapper.ArrayMapper; import com.thoughtworks.xstream.mapper.AttributeAliasingMapper; import com.thoughtworks.xstream.mapper.AttributeMapper; import com.thoughtworks.xstream.mapper.CachingMapper; import com.thoughtworks.xstream.mapper.ClassAliasingMapper; import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper; import com.thoughtworks.xstream.mapper.DefaultMapper; import com.thoughtworks.xstream.mapper.DynamicProxyMapper; import com.thoughtworks.xstream.mapper.FieldAliasingMapper; import com.thoughtworks.xstream.mapper.ImmutableTypesMapper; import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper; import com.thoughtworks.xstream.mapper.LocalConversionMapper; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.mapper.OuterClassMapper; import com.thoughtworks.xstream.mapper.PackageAliasingMapper; import com.thoughtworks.xstream.mapper.SystemAttributeAliasingMapper; import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper; /** * Simple facade to XStream library, a Java-XML serialization tool. <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * XStream xstream = new XStream(); * String xml = xstream.toXML(myObject); // serialize to XML * Object myObject2 = xstream.fromXML(xml); // deserialize from XML * </pre> * * </blockquote> * <hr> * <p/> * <h3>Aliasing classes</h3> * <p/> * <p> * To create shorter XML, you can specify aliases for classes using the <code>alias()</code> * method. For example, you can shorten all occurrences of element * <code>&lt;com.blah.MyThing&gt;</code> to <code>&lt;my-thing&gt;</code> by registering an * alias for the class. * <p> * <hr> * <blockquote> * * <pre> * xstream.alias(&quot;my-thing&quot;, MyThing.class); * </pre> * * </blockquote> * <hr> * <p/> * <h3>Converters</h3> * <p/> * <p> * XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each * of which acts as a strategy for converting a particular type of class to XML and back again. Out * of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc) * and collections (Map, List, Set, Properties, etc). For other objects reflection is used to * serialize each field recursively. * </p> * <p/> * <p> * Extra converters can be registered using the <code>registerConverter()</code> method. Some * non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended} * package and you can create your own by implementing the * {@link com.thoughtworks.xstream.converters.Converter} interface. * </p> * <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new SqlTimestampConverter()); * xstream.registerConverter(new DynamicProxyConverter()); * </pre> * * </blockquote> * <hr> * <p> * The converters can be registered with an explicit priority. By default they are registered with * XStream.PRIORITY_NORMAL. Converters of same priority will be used in the reverse sequence * they have been registered. The default converter, i.e. the converter which will be used if * no other registered converter is suitable, can be registered with priority * XStream.PRIORITY_VERY_LOW. XStream uses by default the * {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the fallback * converter. * </p> * <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new CustomDefaultConverter(), XStream.PRIORITY_VERY_LOW); * </pre> * * </blockquote> * <hr> * <p/> * <h3>Object graphs</h3> * <p/> * <p> * XStream has support for object graphs; a deserialized object graph will keep references intact, * including circular references. * </p> * <p/> * <p> * XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using * <code>setMode()</code>: * </p> * <p/> * <table border='1'> * <tr> * <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td> * <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML * with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate * references. This produces XML with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.SINGLE_NODE_XPATH_RELATIVE_REFERENCES);</code></td> * <td>Uses XPath relative references to signify duplicate references. The XPath expression ensures that * a single node only is selected always.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate references. The XPath expression ensures that * a single node only is selected always.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td> * <td>Uses ID references to signify duplicate references. In some scenarios, such as when using * hand-written XML, this is easier to work with.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td> * <td>This disables object graph support and treats the object structure like a tree. Duplicate * references are treated as two separate objects and circular references cause an exception. This * is slightly faster and uses less memory than the other two modes.</td> * </tr> * </table> * <h3>Thread safety</h3> * <p> * The XStream instance is thread-safe. That is, once the XStream instance has been created and * configured, it may be shared across multiple threads allowing objects to be * serialized/deserialized concurrently. <em>Note, that this only applies if annotations are not * auto-detected on -the-fly.</em> * </p> * <h3>Implicit collections</h3> * <p/> * <p> * To avoid the need for special tags for collections, you can define implicit collections using one * of the <code>addImplicitCollection</code> methods. * </p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Mauro Talevi * @author Guilherme Silveira */ public class XStream { // CAUTION: The sequence of the fields is intentional for an optimal XML output of a // self-serialization! private ReflectionProvider reflectionProvider; private HierarchicalStreamDriver hierarchicalStreamDriver; private ClassLoaderReference classLoaderReference; private MarshallingStrategy marshallingStrategy; private ConverterLookup converterLookup; private ConverterRegistry converterRegistry; private Mapper mapper; private PackageAliasingMapper packageAliasingMapper; private ClassAliasingMapper classAliasingMapper; private FieldAliasingMapper fieldAliasingMapper; private AttributeAliasingMapper attributeAliasingMapper; private SystemAttributeAliasingMapper systemAttributeAliasingMapper; private AttributeMapper attributeMapper; private DefaultImplementationsMapper defaultImplementationsMapper; private ImmutableTypesMapper immutableTypesMapper; private ImplicitCollectionMapper implicitCollectionMapper; private LocalConversionMapper localConversionMapper; private AnnotationConfiguration annotationConfiguration; private transient JVM jvm = new JVM(); public static final int NO_REFERENCES = 1001; public static final int ID_REFERENCES = 1002; public static final int XPATH_RELATIVE_REFERENCES = 1003; public static final int XPATH_ABSOLUTE_REFERENCES = 1004; public static final int SINGLE_NODE_XPATH_RELATIVE_REFERENCES = 1005; public static final int SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES = 1006; public static final int PRIORITY_VERY_HIGH = 10000; public static final int PRIORITY_NORMAL = 0; public static final int PRIORITY_LOW = -10; public static final int PRIORITY_VERY_LOW = -20; private static final String ANNOTATION_MAPPER_TYPE = "com.thoughtworks.xstream.mapper.AnnotationMapper"; /** * Constructs a default XStream. The instance will use the {@link XppDriver} as default and * tries to determine the best match for the {@link ReflectionProvider} on its own. * * @throws InitializationException in case of an initialization problem */ public XStream() { this(null, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link ReflectionProvider}. The instance will use * the {@link XppDriver} as default. * * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will * tries to determine the best match for the {@link ReflectionProvider} on its own. * * @throws InitializationException in case of an initialization problem */ public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and * {@link ReflectionProvider}. * * @throws InitializationException in case of an initialization problem */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and * {@link ReflectionProvider} and additionally with a prepared {@link Mapper}. * * @throws InitializationException in case of an initialization problem * @deprecated As of 1.3, use * {@link #XStream(ReflectionProvider, HierarchicalStreamDriver, ClassLoader, Mapper)} * instead */ public XStream( ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { this( reflectionProvider, driver, new ClassLoaderReference(new CompositeClassLoader()), mapper, new DefaultConverterLookup(), null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and * {@link ReflectionProvider} and additionally with a prepared {@link ClassLoader} to use. * * @throws InitializationException in case of an initialization problem * @since 1.3 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) { this(reflectionProvider, driver, classLoader, null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and * {@link ReflectionProvider} and additionally with a prepared {@link Mapper} and the * {@link ClassLoader} in use. * <p> * Note, if the class loader should be changed later again, you should provide a * {@link ClassLoaderReference} as {@link ClassLoader} that is also use in the * {@link Mapper} chain. * </p> * * @throws InitializationException in case of an initialization problem * @since 1.3 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper) { this( reflectionProvider, driver, classLoader, mapper, new DefaultConverterLookup(), null); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}, * {@link ReflectionProvider}, a prepared {@link Mapper} and the {@link ClassLoader} in use * and an own {@link ConverterRegistry}. * <p> * Note, if the class loader should be changed later again, you should provide a * {@link ClassLoaderReference} as {@link ClassLoader} that is also use in the * {@link Mapper} chain. * </p> * * @throws InitializationException in case of an initialization problem * @since 1.3 */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { jvm = new JVM(); if (reflectionProvider == null) { reflectionProvider = jvm.bestReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = classLoader instanceof ClassLoaderReference ? (ClassLoaderReference)classLoader : new ClassLoaderReference(classLoader); this.converterLookup = converterLookup; this.converterRegistry = converterRegistry != null ? converterRegistry : (converterLookup instanceof ConverterRegistry ? (ConverterRegistry)converterLookup : null); this.mapper = mapper == null ? buildMapper() : mapper; setupMappers(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if (useXStream11XmlFriendlyMapper()) { mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new DynamicProxyMapper(mapper); mapper = new PackageAliasingMapper(mapper); mapper = new ClassAliasingMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new SystemAttributeAliasingMapper(mapper); mapper = new ImplicitCollectionMapper(mapper); mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new AttributeMapper(mapper, converterLookup, reflectionProvider); if (JVM.is15()) { mapper = buildMapperDynamically( "com.thoughtworks.xstream.mapper.EnumMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new LocalConversionMapper(mapper); mapper = new ImmutableTypesMapper(mapper); if (JVM.is15()) { mapper = buildMapperDynamically(ANNOTATION_MAPPER_TYPE, new Class[]{ Mapper.class, ConverterRegistry.class, ClassLoader.class, ReflectionProvider.class, JVM.class}, new Object[]{ mapper, converterLookup, classLoaderReference, reflectionProvider, jvm}); } mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } private Mapper buildMapperDynamically(String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException( "Could not instantiate mapper : " + className, e); } } protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } protected boolean useXStream11XmlFriendlyMapper() { return false; } private void setupMappers() { packageAliasingMapper = (PackageAliasingMapper)this.mapper .lookupMapperOfType(PackageAliasingMapper.class); classAliasingMapper = (ClassAliasingMapper)this.mapper .lookupMapperOfType(ClassAliasingMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper .lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper .lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); systemAttributeAliasingMapper = (SystemAttributeAliasingMapper)this.mapper .lookupMapperOfType(SystemAttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper .lookupMapperOfType(ImmutableTypesMapper.class); localConversionMapper = (LocalConversionMapper)this.mapper .lookupMapperOfType(LocalConversionMapper.class); annotationConfiguration = (AnnotationConfiguration)this.mapper .lookupMapperOfType(AnnotationConfiguration.class); } protected void setupAliases() { if (classAliasingMapper == null) { return; } alias("null", Mapper.Null.class); alias("int", Integer.class); alias("float", Float.class); alias("double", Double.class); alias("long", Long.class); alias("short", Short.class); alias("char", Character.class); alias("byte", Byte.class); alias("boolean", Boolean.class); alias("number", Number.class); alias("object", Object.class); alias("big-int", BigInteger.class); alias("big-decimal", BigDecimal.class); alias("string-buffer", StringBuffer.class); alias("string", String.class); alias("java-class", Class.class); alias("method", Method.class); alias("constructor", Constructor.class); alias("field", Field.class); alias("date", Date.class); alias("uri", URI.class); alias("url", URL.class); alias("bit-set", BitSet.class); alias("map", Map.class); alias("entry", Map.Entry.class); alias("properties", Properties.class); alias("list", List.class); alias("set", Set.class); alias("sorted-set", SortedSet.class); alias("linked-list", LinkedList.class); alias("vector", Vector.class); alias("tree-map", TreeMap.class); alias("tree-set", TreeSet.class); alias("hashtable", Hashtable.class); if (jvm.supportsAWT()) { // Instantiating these two classes starts the AWT system, which is undesirable. // Calling loadClass ensures a reference to the class is found but they are not // instantiated. alias("awt-color", jvm.loadClass("java.awt.Color")); alias("awt-font", jvm.loadClass("java.awt.Font")); alias("awt-text-attribute", jvm.loadClass("java.awt.font.TextAttribute")); } if (jvm.supportsSQL()) { alias("sql-timestamp", jvm.loadClass("java.sql.Timestamp")); alias("sql-time", jvm.loadClass("java.sql.Time")); alias("sql-date", jvm.loadClass("java.sql.Date")); } alias("file", File.class); alias("locale", Locale.class); alias("gregorian-calendar", Calendar.class); if (JVM.is14()) { aliasDynamically("auth-subject", "javax.security.auth.Subject"); alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap")); alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet")); alias("trace", jvm.loadClass("java.lang.StackTraceElement")); alias("currency", jvm.loadClass("java.util.Currency")); aliasType("charset", jvm.loadClass("java.nio.charset.Charset")); } if (JVM.is15()) { aliasDynamically("duration", "javax.xml.datatype.Duration"); alias("enum-set", jvm.loadClass("java.util.EnumSet")); alias("enum-map", jvm.loadClass("java.util.EnumMap")); alias("string-builder", jvm.loadClass("java.lang.StringBuilder")); alias("uuid", jvm.loadClass("java.util.UUID")); } } private void aliasDynamically(String alias, String className) { Class type = jvm.loadClass(className); if (type != null) { alias(alias, type); } } protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(TreeSet.class, SortedSet.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } protected void setupConverters() { final ReflectionConverter reflectionConverter = new ReflectionConverter( mapper, reflectionProvider); registerConverter(reflectionConverter, PRIORITY_VERY_LOW); registerConverter( new SerializableConverter(mapper, reflectionProvider, classLoaderReference), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper, classLoaderReference), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URIConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter((Converter)new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if (jvm.supportsSQL()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter( new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaFieldConverter(classLoaderReference), PRIORITY_NORMAL); if (jvm.supportsAWT()) { registerConverter(new FontConverter(), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } if (jvm.supportsSwing()) { registerConverter( new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); if (JVM.is14()) { // late bound converters - allows XStream to be compiled on earlier JDKs registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.SubjectConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL, new Class[]{Converter.class}, new Object[]{reflectionConverter}); registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, new Class[]{Converter.class}, new Object[]{reflectionConverter}); registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.CharsetConverter", PRIORITY_NORMAL, null, null); } if (JVM.is15()) { // late bound converters - allows XStream to be compiled on earlier JDKs if (jvm.loadClass("javax.xml.datatype.Duration") != null) { registerConverterDynamically( "com.thoughtworks.xstream.converters.extended.DurationConverter", PRIORITY_NORMAL, null, null); } registerConverterDynamically( "com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( "com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( "com.thoughtworks.xstream.converters.basic.StringBuilderConverter", PRIORITY_NORMAL, null, null); registerConverterDynamically( "com.thoughtworks.xstream.converters.basic.UUIDConverter", PRIORITY_NORMAL, null, null); } registerConverter( new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL); } private void registerConverterDynamically(String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException( "Could not instantiate converter : " + className, e); } } protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class); addImmutableType(Boolean.class); addImmutableType(byte.class); addImmutableType(Byte.class); addImmutableType(char.class); addImmutableType(Character.class); addImmutableType(double.class); addImmutableType(Double.class); addImmutableType(float.class); addImmutableType(Float.class); addImmutableType(int.class); addImmutableType(Integer.class); addImmutableType(long.class); addImmutableType(Long.class); addImmutableType(short.class); addImmutableType(Short.class); // additional types addImmutableType(Mapper.Null.class); addImmutableType(BigDecimal.class); addImmutableType(BigInteger.class); addImmutableType(String.class); addImmutableType(URI.class); addImmutableType(URL.class); addImmutableType(File.class); addImmutableType(Class.class); if (jvm.supportsAWT()) { addImmutableTypeDynamically("java.awt.font.TextAttribute"); } if (JVM.is14()) { // late bound types - allows XStream to be compiled on earlier JDKs addImmutableTypeDynamically("java.nio.charset.Charset"); addImmutableTypeDynamically("java.util.Currency"); } } private void addImmutableTypeDynamically(String className) { Class type = jvm.loadClass(className); if (type != null) { addImmutableType(type); } } public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } /** * Serialize an object to a pretty-printed XML String. * * @throws XStreamException if the object cannot be serialized */ public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } /** * Serialize an object to the given Writer as pretty-printed XML. The Writer will be flushed * afterwards and in case of an exception. * * @throws XStreamException if the object cannot be serialized */ public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } /** * Serialize an object to the given OutputStream as pretty-printed XML. The OutputStream * will be flushed afterwards and in case of an exception. * * @throws XStreamException if the object cannot be serialized */ public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } /** * Serialize and object to a hierarchical data structure (such as XML). * * @throws XStreamException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } /** * Serialize and object to a hierarchical data structure (such as XML). * * @param dataHolder Extra data you can use to pass to your converters. Use this as you * want. If not present, XStream shall create one lazily as needed. * @throws XStreamException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } /** * Deserialize an object from an XML String. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } /** * Deserialize an object from an XML Reader. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(Reader reader) { return unmarshal(hierarchicalStreamDriver.createReader(reader), null); } /** * Deserialize an object from an XML InputStream. * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } /** * Deserialize an object from a URL. * * Depending on the parser implementation, some might take the file path as SystemId to * resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since upcoming */ public Object fromXML(URL url) { return unmarshal(hierarchicalStreamDriver.createReader(url), null); } /** * Deserialize an object from a file. * * Depending on the parser implementation, some might take the file path as SystemId to * resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since upcoming */ public Object fromXML(File file) { return unmarshal(hierarchicalStreamDriver.createReader(file), null); } /** * Deserialize an object from an XML String, populating the fields of the given root object * instead of instantiating a new one. Note, that this is a special use case! With the * ReflectionConverter XStream will write directly into the raw memory area of the existing * object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } /** * Deserialize an object from an XML Reader, populating the fields of the given root object * instead of instantiating a new one. Note, that this is a special use case! With the * ReflectionConverter XStream will write directly into the raw memory area of the existing * object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from a URL, populating the fields of the given root * object instead of instantiating a new one. Note, that this is a special use case! With * the ReflectionConverter XStream will write directly into the raw memory area of the * existing object. Use with care! * * Depending on the parser implementation, some might take the file path as SystemId to * resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since upcoming */ public Object fromXML(URL url, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(url), root); } /** * Deserialize an object from a file, populating the fields of the given root * object instead of instantiating a new one. Note, that this is a special use case! With * the ReflectionConverter XStream will write directly into the raw memory area of the * existing object. Use with care! * * Depending on the parser implementation, some might take the file path as SystemId to * resolve additional references. * * @throws XStreamException if the object cannot be deserialized * @since upcoming */ public Object fromXML(File file, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(file), root); } /** * Deserialize an object from an XML InputStream, populating the fields of the given root * object instead of instantiating a new one. Note, that this is a special use case! With * the ReflectionConverter XStream will write directly into the raw memory area of the * existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object fromXML(InputStream input, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(input), root); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } /** * Deserialize an object from a hierarchical data structure (such as XML), populating the * fields of the given root object instead of instantiating a new one. Note, that this is a * special use case! With the ReflectionConverter XStream will write directly into the raw * memory area of the existing object. Use with care! * * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @param root If present, the passed in object will have its fields populated, as opposed * to XStream creating a new instance. Note, that this is a special use case! * With the ReflectionConverter XStream will write directly into the raw memory * area of the existing object. Use with care! * @param dataHolder Extra data you can use to pass to your converters. Use this as you * want. If not present, XStream shall create one lazily as needed. * @throws XStreamException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { try { return marshallingStrategy.unmarshal( root, reader, dataHolder, converterLookup, mapper); } catch (ConversionException e) { Package pkg = getClass().getPackage(); e.add("version", pkg != null ? pkg.getImplementationVersion() : "not available"); throw e; } } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addClassAlias(name, type); } /** * Alias a type to a shorter name to be used in XML elements. Any class that is assignable * to this type will be aliased to the same name. * * @param name Short name * @param type Type to be aliased * @since 1.2 * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addTypeAlias(name, type); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @param defaultImplementation Default implementation of type to use if no other specified. * @throws InitializationException if no {@link DefaultImplementationsMapper} or no * {@link ClassAliasingMapper} is available */ public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } /** * Alias a package to a shorter name to be used in XML elements. * * @param name Short name * @param pkgName package to be aliased * @throws InitializationException if no {@link DefaultImplementationsMapper} or no * {@link PackageAliasingMapper} is available * @since 1.3.1 */ public void aliasPackage(String name, String pkgName) { if (packageAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + PackageAliasingMapper.class.getName() + " available"); } packageAliasingMapper.addPackageAlias(name, pkgName); } /** * Create an alias for a field name. * * @param alias the alias itself * @param definedIn the type that declares the field * @param fieldName the name of the field * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void aliasField(String alias, Class definedIn, String fieldName) { if (fieldAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.addFieldAlias(alias, definedIn, fieldName); } /** * Create an alias for an attribute * * @param alias the alias itself * @param attributeName the name of the attribute * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(attributeName, alias); } /** * Create an alias for a system attribute. XStream will not write a system attribute if its * alias is set to <code>null</code>. However, this is not reversible, i.e. deserialization * of the result is likely to fail afterwards and will not produce an object equal to the * originally written one. * * @param alias the alias itself (may be <code>null</code>) * @param systemAttributeName the name of the system attribute * @throws InitializationException if no {@link SystemAttributeAliasingMapper} is available * @since 1.3.1 */ public void aliasSystemAttribute(String alias, String systemAttributeName) { if (systemAttributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + SystemAttributeAliasingMapper.class.getName() + " available"); } systemAttributeAliasingMapper.addAliasFor(systemAttributeName, alias); } /** * Create an alias for an attribute. * * @param definedIn the type where the attribute is defined * @param attributeName the name of the attribute * @param alias the alias itself * @throws InitializationException if no {@link AttributeAliasingMapper} is available * @since 1.2.2 */ public void aliasAttribute(Class definedIn, String attributeName, String alias) { aliasField(alias, definedIn, attributeName); useAttributeFor(definedIn, attributeName); } /** * Use an attribute for a field or a specific type. * * @param fieldName the name of the field * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(fieldName, type); } /** * Use an attribute for a field declared in a specific type. * * @param fieldName the name of the field * @param definedIn the Class containing such field * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2.2 */ public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(definedIn, fieldName); } /** * Use an attribute for an arbitrary type. * * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(type); } /** * Associate a default implementation of a class with an object. Whenever XStream encounters * an instance of this type, it will use the default implementation instead. For example, * java.util.ArrayList is the default implementation of java.util.List. * * @param defaultImplementation * @param ofType * @throws InitializationException if no {@link DefaultImplementationsMapper} is available */ public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + DefaultImplementationsMapper.class.getName() + " available"); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } /** * Add immutable types. The value of the instances of these types will always be written * into the stream even if they appear multiple times. * * @throws InitializationException if no {@link ImmutableTypesMapper} is available */ public void addImmutableType(Class type) { if (immutableTypesMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImmutableTypesMapper.class.getName() + " available"); } immutableTypesMapper.addImmutableType(type); } public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(Converter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(converter, priority); } } public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(SingleValueConverter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter( new SingleValueConverterWrapper(converter), priority); } } /** * Register a local {@link Converter} for a field. * * @param definedIn the class type the field is defined in * @param fieldName the field name * @param converter the converter to use * @since 1.3 */ public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) { if (localConversionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + LocalConversionMapper.class.getName() + " available"); } localConversionMapper.registerLocalConverter(definedIn, fieldName, converter); } /** * Register a local {@link SingleValueConverter} for a field. * * @param definedIn the class type the field is defined in * @param fieldName the field name * @param converter the converter to use * @since 1.3 */ public void registerLocalConverter(Class definedIn, String fieldName, SingleValueConverter converter) { registerLocalConverter( definedIn, fieldName, (Converter)new SingleValueConverterWrapper(converter)); } /** * Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper * MapperWrappers}. * * @return the mapper * @since 1.2 */ public Mapper getMapper() { return mapper; } /** * Retrieve the {@link ReflectionProvider} in use. * * @return the mapper * @since 1.2.1 */ public ReflectionProvider getReflectionProvider() { return reflectionProvider; } public ConverterLookup getConverterLookup() { return converterLookup; } public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; case SINGLE_NODE_XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; case SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; default: throw new IllegalArgumentException("Unknown mode : " + mode); } } /** * Adds a default implicit collection which is used for any unmapped XML tag. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete * collection type or matching the default implementation type of the collection * type. */ public void addImplicitCollection(Class ownerType, String fieldName) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, null, null); } /** * Adds implicit collection which is used for all items of the given itemType. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete * collection type or matching the default implementation type of the collection * type. * @param itemType type of the items to be part of this collection. * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, null, itemType); } /** * Adds implicit collection which is used for all items of the given element name defined by * itemFieldName. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be a concrete * collection type or matching the default implementation type of the collection * type. * @param itemFieldName element name of the implicit collection * @param itemType item type to be aliases be the itemFieldName * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType); } /** * Adds an implicit array. * * @param ownerType class owning the implicit array * @param fieldName name of the array field * @since upcoming */ public void addImplicitArray(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName); } /** * Adds an implicit array which is used for all items of the given itemType when the array * type matches. * * @param ownerType class owning the implicit array * @param fieldName name of the array field in the ownerType * @param itemType type of the items to be part of this array * @throws InitializationException if no {@link ImplicitCollectionMapper} is available or the * array type does not match the itemType * @since upcoming */ public void addImplicitArray(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, itemType); } /** * Adds an implicit array which is used for all items of the given element name defined by * itemName. * * @param ownerType class owning the implicit array * @param fieldName name of the array field in the ownerType * @param itemName alias name of the items * @throws InitializationException if no {@link ImplicitCollectionMapper} is available * @since upcoming */ public void addImplicitArray(Class ownerType, String fieldName, String itemName) { addImplicitCollection(ownerType, fieldName, itemName, null); } /** * Create a DataHolder that can be used to pass data to the converters. The DataHolder is * provided with a call to {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)} or * {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)}. * * @return a new {@link DataHolder} */ public DataHolder newDataHolder() { return new MapBackedDataHolder(); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(writer), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(writer), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream * using XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.3 */ public ObjectOutputStream createObjectOutputStream(OutputStream out) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(out), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the OutputStream * using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.3 */ public ObjectOutputStream createObjectOutputStream(OutputStream out, String rootNodeName) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(out), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * Because an ObjectOutputStream can contain multiple items and XML only allows a single * root node, the stream must be written inside an enclosing node. * </p> * <p> * It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will * be incomplete. * </p> * <h3>Example</h3> * * <pre> * ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, &quot;things&quot;); * out.writeInt(123); * out.writeObject(&quot;Hello&quot;); * out.writeObject(someObject) * out.close(); * </pre> * * @param writer The writer to serialize the objects to. * @param rootNodeName The name of the root node enclosing the stream of objects. * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, String rootNodeName) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(Object object) { marshal(object, statefulWriter); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using * XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from an InputStream * using XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @since 1.3 */ public ObjectInputStream createObjectInputStream(InputStream in) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(in)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using * XStream. <h3>Example</h3> * * <pre> * ObjectInputStream in = xstream.createObjectOutputStream(aReader); * int a = out.readInt(); * Object b = out.readObject(); * Object c = out.readObject(); * </pre> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, * String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); Object result = unmarshal(reader); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException("not in call to readObject"); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException("not in call to readObject"); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException("stream inactive"); } public void close() { reader.close(); } }, classLoaderReference); } /** * Change the ClassLoader XStream uses to load classes. Creating an XStream instance it will * register for all kind of classes and types of the current JDK, but not for any 3rd party * type. To ensure that all other types are loaded with your class loader, you should call * this method as early as possible - or consider to provide the class loader directly in * the constructor. * * @since 1.1.1 */ public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } /** * Retrieve the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } /** * Prevents a field from being serialized. To omit a field you must always provide the * declaring type and not necessarily the type that is converted. * * @since 1.1.3 * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void omitField(Class definedIn, String fieldName) { if (fieldAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.omitField(definedIn, fieldName); } /** * Process the annotations of the given types and configure the XStream. * * @param types the types with XStream annotations * @since 1.3 */ public void processAnnotations(final Class[] types) { if (annotationConfiguration == null) { throw new com.thoughtworks.xstream.InitializationException("No " + ANNOTATION_MAPPER_TYPE + " available"); } annotationConfiguration.processAnnotations(types); } /** * Process the annotations of the given type and configure the XStream. A call of this * method will automatically turn the auto-detection mode for annotations off. * * @param type the type with XStream annotations * @since 1.3 */ public void processAnnotations(final Class type) { processAnnotations(new Class[]{type}); } /** * Set the auto-detection mode of the AnnotationMapper. Note that auto-detection implies * that the XStream is configured while it is processing the XML steams. This is a potential * concurrency problem. Also is it technically not possible to detect all class aliases at * deserialization. You have been warned! * * @param mode <code>true</code> if annotations are auto-detected * @since 1.3 */ public void autodetectAnnotations(boolean mode) { if (annotationConfiguration != null) { annotationConfiguration.autodetectAnnotations(mode); } } /** * @deprecated As of 1.3, use {@link InitializationException} instead */ public static class InitializationException extends XStreamException { /** * @deprecated As of 1.3, use {@link InitializationException} instead */ public InitializationException(String message, Throwable cause) { super(message, cause); } /** * @deprecated As of 1.3, use {@link InitializationException} instead */ public InitializationException(String message) { super(message); } } private Object readResolve() { jvm = new JVM(); return this; } }
package org.apache.fop.fo.expr; import org.apache.fop.fo.Property; import org.apache.fop.fo.LengthProperty; import org.apache.fop.datatypes.TableColLength; /** * Class modelling the proportional-column-width function. See Sec. 5.10.4 of * the XSL-FO standard. */ public class PPColWidthFunction extends FunctionBase { /** * @return 1 (the number of arguments for the proportional-column-width * function) */ public int nbArgs() { return 1; } /** * * @param args array of arguments for this function * @param pInfo PropertyInfo for this function * @return numeric Property containing the units of proportional measure * for this column * @throws PropertyException for non-numeric operand, or if the parent * element is not a table-column */ public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number d = args[0].getNumber(); if (d == null) { throw new PropertyException("Non numeric operand to " + "proportional-column-width function"); } if (!pInfo.getPropertyList().getElement().equals("fo:table-column")) { throw new PropertyException("proportional-column-width function " + "may only be used on table-column FO"); } // Check if table-layout is "fixed"... return new LengthProperty(new TableColLength(d.doubleValue())); } }
package org.joda.time.field; import java.io.Serializable; import java.util.Locale; import org.joda.time.DateTimeField; import org.joda.time.DurationField; import org.joda.time.partial.PartialInstant; /** * AbstractDateTimeField provides the common behaviour for DateTimeField * implementations. * <p> * This class should generally not be used directly by API users. The * DateTimeField interface should be used when different kinds of DateTimeField * objects are to be referenced. * <p> * AbstractDateTimeField is thread-safe and immutable, and its subclasses must * be as well. * * @author Brian S O'Neill * @since 1.0 * @see DecoratedDateTimeField */ public abstract class AbstractDateTimeField extends DateTimeField implements Serializable { /** Serialization version */ private static final long serialVersionUID = -4388055220581798589L; /** A desriptive name for the field */ private final String iName; /** * Constructor. */ protected AbstractDateTimeField(String name) { super(); if (name == null) { throw new IllegalArgumentException("The name must not be null"); } iName = name; } public final String getName() { return iName; } /** * @return true always */ public final boolean isSupported() { return true; } // Main access API /** * Get the value of this field from the milliseconds. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the value of the field, in the units of the field */ public abstract int get(long instant); /** * Get the human-readable, text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsText(get(instant), locale). * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null for * default * @return the text value of the field */ public String getAsText(long instant, Locale locale) { return getAsText(get(instant), locale); } /** * Get the human-readable, text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsText(fieldValue, locale). * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsText(PartialInstant partial, int fieldValue, Locale locale) { return getAsText(fieldValue, locale); } /** * Get the human-readable, text value of this field from the field value. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns Integer.toString(get(instant)). * <p> * Note: subclasses that override this method should also override * getMaximumTextLength. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ protected String getAsText(int fieldValue, Locale locale) { return Integer.toString(fieldValue); } /** * Get the human-readable, short text value of this field from the milliseconds. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsShortText(get(instant), locale). * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsShortText(long instant, Locale locale) { return getAsShortText(get(instant), locale); } /** * Get the human-readable, short text value of this field from a partial instant. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsShortText(fieldValue, locale). * * @param partial the partial instant to query * @param fieldValue the field value of this field, provided for performance * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ public String getAsShortText(PartialInstant partial, int fieldValue, Locale locale) { return getAsShortText(fieldValue, locale); } /** * Get the human-readable, short text value of this field from the field value. * If the specified locale is null, the default locale is used. * <p> * The default implementation returns getAsText(fieldValue, locale). * <p> * Note: subclasses that override this method should also override * getMaximumShortTextLength. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @param locale the locale to use for selecting a text symbol, null for default * @return the text value of the field */ protected String getAsShortText(int fieldValue, Locale locale) { return getAsText(fieldValue, locale); } /** * Adds a value (which may be negative) to the instant value, * overflowing into larger fields if necessary. * <p> * The value will be added to this field. If the value is too large to be * added solely to this field, larger fields will increase as required. * Smaller fields should be unaffected, except where the result would be * an invalid value for a smaller field. In this case the smaller field is * adjusted to be in range. * <p> * For example, in the ISO chronology:<br> * 2000-08-20 add six months is 2001-02-20<br> * 2000-08-20 add twenty months is 2002-04-20<br> * 2000-08-20 add minus nine months is 1999-11-20<br> * 2001-01-31 add one month is 2001-02-28<br> * 2001-01-31 add two months is 2001-03-31<br> * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public long add(long instant, int value) { return getDurationField().add(instant, value); } public long add(long instant, long value) { return getDurationField().add(instant, value); } /** * Adds a value (which may be negative) to the instant value, * wrapping within this field. * <p> * The value will be added to this field. If the value is too large to be * added solely to this field then it wraps. Larger fields are always * unaffected. Smaller fields should be unaffected, except where the * result would be an invalid value for a smaller field. In this case the * smaller field is adjusted to be in range. * <p> * For example, in the ISO chronology:<br> * 2000-08-20 addWrapped six months is 2000-02-20<br> * 2000-08-20 addWrapped twenty months is 2000-04-20<br> * 2000-08-20 addWrapped minus nine months is 2000-11-20<br> * 2001-01-31 addWrapped one month is 2001-02-28<br> * 2001-01-31 addWrapped two months is 2001-03-31<br> * <p> * The default implementation internally calls set. Subclasses are * encouraged to provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to add to * @param value the value to add, in the units of the field * @return the updated milliseconds */ public long addWrapped(long instant, int value) { int current = get(instant); int wrapped = FieldUtils.getWrappedValue (current, value, getMinimumValue(instant), getMaximumValue(instant)); return set(instant, wrapped); } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * * <pre> * long instant = ... * int v = ... * int age = getDifference(add(instant, v), instant); * </pre> * * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public int getDifference(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifference(minuendInstant, subtrahendInstant); } /** * Computes the difference between two instants, as measured in the units * of this field. Any fractional units are dropped from the result. Calling * getDifference reverses the effect of calling add. In the following code: * * <pre> * long instant = ... * long v = ... * long age = getDifferenceAsLong(add(instant, v), instant); * </pre> * * The value 'age' is the same as the value 'v'. * * @param minuendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract from * @param subtrahendInstant the milliseconds from 1970-01-01T00:00:00Z to * subtract off the minuend * @return the difference in the units of this field */ public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return getDurationField().getDifferenceAsLong(minuendInstant, subtrahendInstant); } public abstract long set(long instant, int value); public long set(long instant, String text, Locale locale) { try { return set(instant, Integer.parseInt(text)); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Invalid " + getName() + " text: " + text); } } // Extra information API /** * Returns the duration per unit value of this field. For example, if this * field represents "hour of day", then the unit duration is an hour. * * @return the duration of this field, or UnsupportedDurationField if field * has no duration */ public abstract DurationField getDurationField(); /** * Returns the range duration of this field. For example, if this field * represents "hour of day", then the range duration is a day. * * @return the range duration of this field, or null if field has no range */ public abstract DurationField getRangeDurationField(); /** * Returns whether this field is 'leap' for the specified instant. * <p> * For example, a leap year would return true, a non leap year would return * false. * <p> * This implementation returns false. * * @return true if the field is 'leap' */ public boolean isLeap(long instant) { return false; } /** * Gets the amount by which this field is 'leap' for the specified instant. * <p> * For example, a leap year would return one, a non leap year would return * zero. * <p> * This implementation returns zero. */ public int getLeapAmount(long instant) { return 0; } /** * If this field were to leap, then it would be in units described by the * returned duration. If this field doesn't ever leap, null is returned. * <p> * This implementation returns null. */ public DurationField getLeapDurationField() { return null; } /** * Get the minimum allowable value for this field. * * @return the minimum valid value for this field, in the units of the * field */ public abstract int getMinimumValue(); /** * Get the minimum value for this field evaluated at the specified time. * <p> * This implementation returns the same as {@link #getMinimumValue()}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the minimum value for this field, in the units of the field */ public int getMinimumValue(long instant) { return getMinimumValue(); } /** * Get the maximum allowable value for this field. * * @return the maximum valid value for this field, in the units of the * field */ public abstract int getMaximumValue(); /** * Get the maximum value for this field evaluated at the specified time. * <p> * This implementation returns the same as {@link #getMaximumValue()}. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to query * @return the maximum value for this field, in the units of the field */ public int getMaximumValue(long instant) { return getMaximumValue(); } /** * Get the maximum text value for this field. The default implementation * returns the equivalent of Integer.toString(getMaximumValue()).length(). * * @param locale the locale to use for selecting a text symbol * @return the maximum text length */ public int getMaximumTextLength(Locale locale) { int max = getMaximumValue(); if (max >= 0) { if (max < 10) { return 1; } else if (max < 100) { return 2; } else if (max < 1000) { return 3; } } return Integer.toString(max).length(); } /** * Get the maximum short text value for this field. The default * implementation returns getMaximumTextLength(). * * @param locale the locale to use for selecting a text symbol * @return the maximum short text length */ public int getMaximumShortTextLength(Locale locale) { return getMaximumTextLength(locale); } // Calculation API /** * Round to the lowest whole unit of this field. After rounding, the value * of this field and all fields of a higher magnitude are retained. The * fractional millis that cannot be expressed in whole increments of this * field are set to minimum. * <p> * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * lowest whole hour is 2002-11-02T23:00:00.000. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public abstract long roundFloor(long instant); /** * Round to the highest whole unit of this field. The value of this field * and all fields of a higher magnitude may be incremented in order to * achieve this result. The fractional millis that cannot be expressed in * whole increments of this field are set to minimum. * <p> * For example, a datetime of 2002-11-02T23:34:56.789, rounded to the * highest whole hour is 2002-11-03T00:00:00.000. * <p> * The default implementation calls roundFloor, and if the instant is * modified as a result, adds one field unit. Subclasses are encouraged to * provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundCeiling(long instant) { long newInstant = roundFloor(instant); if (newInstant != instant) { instant = add(newInstant, 1); } return instant; } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor or is exactly halfway, this function * behaves like roundFloor. If the millisecond value is closer to the * ceiling, this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfFloor(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor <= diffToCeiling) { // Closer to the floor, or halfway - round floor return floor; } else { return ceiling; } } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling or is exactly halfway, * this function behaves like roundCeiling. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfCeiling(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffToCeiling <= diffFromFloor) { // Closer to the ceiling, or halfway - round ceiling return ceiling; } else { return floor; } } /** * Round to the nearest whole unit of this field. If the given millisecond * value is closer to the floor, this function behaves like roundFloor. If * the millisecond value is closer to the ceiling, this function behaves * like roundCeiling. * <p> * If the millisecond value is exactly halfway between the floor and * ceiling, the ceiling is chosen over the floor only if it makes this * field's value even. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to round * @return rounded milliseconds */ public long roundHalfEven(long instant) { long floor = roundFloor(instant); long ceiling = roundCeiling(instant); long diffFromFloor = instant - floor; long diffToCeiling = ceiling - instant; if (diffFromFloor < diffToCeiling) { // Closer to the floor - round floor return floor; } else if (diffToCeiling < diffFromFloor) { // Closer to the ceiling - round ceiling return ceiling; } else { // Round to the instant that makes this field even. If both values // make this field even (unlikely), favor the ceiling. if ((get(ceiling) & 1) == 0) { return ceiling; } return floor; } } /** * Returns the fractional duration milliseconds of this field. In other * words, calling remainder returns the duration that roundFloor would * subtract. * <p> * For example, on a datetime of 2002-11-02T23:34:56.789, the remainder by * hour is 34 minutes and 56.789 seconds. * <p> * The default implementation computes * <code>instant - roundFloor(instant)</code>. Subclasses are encouraged to * provide a more efficient implementation. * * @param instant the milliseconds from 1970-01-01T00:00:00Z to get the * remainder * @return remainder duration, in milliseconds */ public long remainder(long instant) { return instant - roundFloor(instant); } /** * Get a suitable debug string. * * @return debug string */ public String toString() { return "DateTimeField[" + getName() + ']'; } }
package org.opentdc.tags.file; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import javax.servlet.ServletContext; import org.opentdc.file.AbstractFileServiceProvider; import org.opentdc.tags.SingleLangTag; import org.opentdc.tags.TagModel; import org.opentdc.tags.ServiceProvider; import org.opentdc.service.LocalizedTextModel; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.InternalServerErrorException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.ValidationException; import org.opentdc.util.LanguageCode; import org.opentdc.util.PrettyPrinter; /** * A file-based or transient implementation of the Tags service. * @author Bruno Kaiser * */ public class FileServiceProvider extends AbstractFileServiceProvider<MultiLangTag> implements ServiceProvider { private static Map<String, MultiLangTag> index = null; private static Map<String, LocalizedTextModel> textIndex = null; private static final Logger logger = Logger.getLogger(FileServiceProvider.class.getName()); /** * Constructor. * @param context the servlet context. * @param prefix the simple class name of the service provider * @throws IOException */ public FileServiceProvider( ServletContext context, String prefix ) throws IOException { super(context, prefix); logger.info("tags-service.FileServiceProvider.Constructor()"); if (index == null) { index = new ConcurrentHashMap<String, MultiLangTag>(); textIndex = new ConcurrentHashMap<String, LocalizedTextModel>(); List<MultiLangTag> _tags = importJson(); for (MultiLangTag _tag : _tags) { index.put(_tag.getModel().getId(), _tag); for (LocalizedTextModel _tm : _tag.getLocalizedTexts()) { textIndex.put(_tm.getId(), _tm); } } logger.info("indexed " + index.size() + " tags and " + textIndex.size() + " localized texts."); } } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#list(java.lang.String, java.lang.String, int, int) */ @Override public ArrayList<SingleLangTag> list( String query, String queryType, int position, int size) { ArrayList<SingleLangTag> _tags = new ArrayList<SingleLangTag>(); LocalizedTextModel _ltm = null; LanguageCode _lc = LanguageCode.getLanguageCodeFromQuery(query); for (MultiLangTag _multiLangTag : index.values()) { if (_lc != null) { // return only the texts in this specific language _ltm = _multiLangTag.getLocalizedText(_lc); if (_ltm != null) { _tags.add(new SingleLangTag(_multiLangTag.getModel().getId(), _ltm, getPrincipal())); } } else { // return all texts in all languages List<LocalizedTextModel> _texts = _multiLangTag.getLocalizedTexts(); for (LocalizedTextModel _lm : _texts) { _tags.add(new SingleLangTag(_multiLangTag.getModel().getId(), _lm, getPrincipal())); } } } Collections.sort(_tags, SingleLangTag.TagComparator); ArrayList<SingleLangTag> _selection = new ArrayList<SingleLangTag>(); for (int i = 0; i < _tags.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_tags.get(i)); } } logger.info("list(<" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " tags."); return _selection; } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#create(org.opentdc.tags.TagModel) */ @Override public TagModel create( TagModel tag) throws DuplicateException, ValidationException { MultiLangTag _multiLangTag = null; logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(tag) + ")"); String _id = tag.getId(); Date _date = new Date(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); tag.setId(_id); tag.setCreatedAt(_date); tag.setCreatedBy(getPrincipal()); tag.setModifiedAt(_date); tag.setModifiedBy(getPrincipal()); _multiLangTag = new MultiLangTag(); _multiLangTag.setModel(tag); } else { _multiLangTag = index.get(_id); if (_multiLangTag != null) { throw new DuplicateException("tag <" + _id + "> exists already."); } else { // a new ID was set on the client; we do not allow this throw new ValidationException("tag <" + _id + "> contains an ID generated on the client. This is not allowed."); } } index.put(_id, _multiLangTag); logger.info("create() -> " + PrettyPrinter.prettyPrintAsJSON(_multiLangTag.getModel())); if (isPersistent) { exportJson(index.values()); } return _multiLangTag.getModel(); } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#read(java.lang.String) */ @Override public TagModel read( String id) throws NotFoundException { TagModel _tag = readMultiLangTag(id).getModel(); logger.info("read(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_tag)); return _tag; } /** * Retrieve a MultiLangTag from the index. * @param id * @return the MultiLangTag * @throws NotFoundException if the index did not contain a MultiLangTag with this id */ public static MultiLangTag readMultiLangTag( String id ) throws NotFoundException { MultiLangTag _multiLangTag = index.get(id); if (_multiLangTag == null) { throw new NotFoundException("tag <" + id + "> was not found."); } logger.info("readMultiLangTag(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_multiLangTag)); return _multiLangTag; } /** * @param id * @param lang * @return * @throws NotFoundException */ public static String getLocalizedText( String id, LanguageCode lang) throws NotFoundException { if (lang == null) { logger.warning("lang is null; using default"); lang = LanguageCode.getDefaultLanguageCode(); } LocalizedTextModel _ltm = readMultiLangTag(id).getLocalizedText(lang); if (_ltm != null) { return _ltm.getText(); } else { return "UNDEFINED"; } } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#update(java.lang.String, org.opentdc.tags.TagModel) */ @Override public TagModel update( String id, TagModel tag ) throws NotFoundException, ValidationException { MultiLangTag _multiLangTag = readMultiLangTag(id); TagModel _tagModel = _multiLangTag.getModel(); if (! _tagModel.getCreatedAt().equals(tag.getCreatedAt())) { logger.warning("tag <" + id + ">: ignoring createdAt value <" + tag.getCreatedAt().toString() + "> because it was set on the client."); } if (! _tagModel.getCreatedBy().equalsIgnoreCase(tag.getCreatedBy())) { logger.warning("tag <" + id + ">: ignoring createdBy value <" + tag.getCreatedBy() + "> because it was set on the client."); } _tagModel.setModifiedAt(new Date()); _tagModel.setModifiedBy(getPrincipal()); _multiLangTag.setModel(_tagModel); index.put(id, _multiLangTag); logger.info("update(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_tagModel)); if (isPersistent) { exportJson(index.values()); } return _tagModel; } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#delete(java.lang.String) */ @Override public void delete( String id) throws NotFoundException, InternalServerErrorException { MultiLangTag _multiLangTag = readMultiLangTag(id); // throws NotFound if (index.remove(id) == null) { throw new InternalServerErrorException("tag <" + id + "> can not be removed, because it does not exist in the index"); } else { // remove was ok // remove all LocalizedTexts members for (LocalizedTextModel _ltm : _multiLangTag.getLocalizedTexts()) { if (textIndex.remove(_ltm.getId()) == null) { throw new InternalServerErrorException("tag <" + id + ">: LocalizedText <" + _ltm.getId() + "> could not be removed, because it does not exist in the index."); } else { logger.info("delete(" + id + "): LocalizedText <" + _ltm.getId() + "> removed from the index."); } } logger.info("delete(" + id + ") -> tag removed from index."); } if (isPersistent) { exportJson(index.values()); } } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#listTexts(java.lang.String, java.lang.String, java.lang.String, int, int) */ @Override public List<LocalizedTextModel> listTexts( String tid, String queryType, String query, int position, int size) { List<LocalizedTextModel> _localizedTexts = readMultiLangTag(tid).getLocalizedTexts(); Collections.sort(_localizedTexts, LocalizedTextModel.LocalizedTextComparator); ArrayList<LocalizedTextModel> _selection = new ArrayList<LocalizedTextModel>(); for (int i = 0; i < _localizedTexts.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_localizedTexts.get(i)); } } logger.info("listTexts(<" + tid + ">, <" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " values"); return _selection; } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#createText(java.lang.String, org.opentdc.service.LocalizedTextModel) */ @Override public LocalizedTextModel createText( String tid, LocalizedTextModel tag) throws DuplicateException, ValidationException { if (tag.getText() == null || tag.getText().isEmpty()) { throw new ValidationException("LocalizedText <" + tid + "/lang/" + tag.getId() + "> must contain a valid text."); } // enforce that the title is a single word StringTokenizer _tokenizer = new StringTokenizer(tag.getText()); if (_tokenizer.countTokens() != 1) { throw new ValidationException("LocalizedText <" + tid + "/lang/" + tag.getId() + "> must consist of exactly one word <" + tag.getText() + "> (is " + _tokenizer.countTokens() + ")."); } MultiLangTag _multiLangTag = readMultiLangTag(tid); if (tag.getLanguageCode() == null) { throw new ValidationException("LocalizedText <" + tid + "/lang/" + tag.getId() + "> must contain a LanguageCode."); } if (_multiLangTag.containsLocalizedText(tag.getLanguageCode())) { throw new DuplicateException("LocalizedText with LanguageCode <" + tag.getLanguageCode() + "> exists already in tag <" + tid + ">."); } String _id = tag.getId(); if (_id == null || _id.isEmpty()) { _id = UUID.randomUUID().toString(); } else { if (textIndex.get(_id) != null) { throw new DuplicateException("LocalizedText with id <" + _id + "> exists alreday in index."); } else { throw new ValidationException("LocalizedText <" + _id + "> contains an ID generated on the client. This is not allowed."); } } tag.setId(_id); Date _date = new Date(); tag.setCreatedAt(_date); tag.setCreatedBy(getPrincipal()); tag.setModifiedAt(_date); tag.setModifiedBy(getPrincipal()); textIndex.put(_id, tag); _multiLangTag.addText(tag); logger.info("createText(" + tid + "/lang/" + tag.getId() + ") -> " + PrettyPrinter.prettyPrintAsJSON(tag)); if (isPersistent) { exportJson(index.values()); } return tag; } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#readText(java.lang.String, java.lang.String) */ @Override public LocalizedTextModel readText( String tid, String lid) throws NotFoundException { readMultiLangTag(tid); LocalizedTextModel _localizedText = textIndex.get(lid); if (_localizedText == null) { throw new NotFoundException("LocalizedText <" + tid + "/lang/" + lid + "> was not found."); } logger.info("readText(" + tid + "/lang/" + lid + ") -> " + PrettyPrinter.prettyPrintAsJSON(_localizedText)); return _localizedText; } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#updateText(java.lang.String, java.lang.String, org.opentdc.service.LocalizedTextModel) */ @Override public LocalizedTextModel updateText( String tid, String lid, LocalizedTextModel tag) throws NotFoundException, ValidationException { readMultiLangTag(tid); LocalizedTextModel _localizedText = textIndex.get(lid); if (_localizedText == null) { throw new NotFoundException("LocalizedText <" + tid + "/lang/" + lid + "> was not found."); } if (tag.getText() == null || tag.getText().isEmpty()) { throw new ValidationException("LocalizedText <" + tid + "/lang/" + lid + "> must contain a valid text."); } // enforce that the title is a single word StringTokenizer _tokenizer = new StringTokenizer(tag.getText()); if (_tokenizer.countTokens() != 1) { throw new ValidationException("LocalizedText <" + tid + "/lang/" + lid + "> must consist of exactly one word <" + tag.getText() + "> (is " + _tokenizer.countTokens() + ")."); } if (! _localizedText.getCreatedAt().equals(tag.getCreatedAt())) { logger.warning("LocalizedText <" + tid + "/lang/" + lid + ">: ignoring createAt value <" + tag.getCreatedAt().toString() + "> because it was set on the client."); } if (! _localizedText.getCreatedBy().equalsIgnoreCase(tag.getCreatedBy())) { logger.warning("LocalizedText <" + tid + "/lang/" + lid + ">: ignoring createBy value <" + tag.getCreatedBy() + "> because it was set on the client."); } if (_localizedText.getLanguageCode() != tag.getLanguageCode()) { throw new ValidationException("LocalizedText <" + tid + "/lang/" + lid + ">: it is not allowed to change the LanguageCode."); } _localizedText.setText(tag.getText()); _localizedText.setModifiedAt(new Date()); _localizedText.setModifiedBy(getPrincipal()); textIndex.put(lid, _localizedText); logger.info("updateText(" + tid + ", " + lid + ") -> " + PrettyPrinter.prettyPrintAsJSON(_localizedText)); if (isPersistent) { exportJson(index.values()); } return _localizedText; } /* (non-Javadoc) * @see org.opentdc.tags.ServiceProvider#deleteText(java.lang.String, java.lang.String) */ @Override public void deleteText( String tid, String lid) throws NotFoundException, InternalServerErrorException { MultiLangTag _multiLangTag = readMultiLangTag(tid); LocalizedTextModel _localizedText = textIndex.get(lid); if (_localizedText == null) { throw new NotFoundException("LocalizedText <" + tid + "/lang/" + lid + "> was not found."); } // 1) remove the LocalizedText from its MultiLangTag if (_multiLangTag.removeText(_localizedText) == false) { throw new InternalServerErrorException("LocalizedText <" + tid + "/lang/" + lid + "> can not be removed, because it is an orphan."); } // 2) remove the LocalizedText from the index if (textIndex.remove(lid) == null) { throw new InternalServerErrorException("LocalizedText <" + tid + "/lang/" + lid + "> can not be removed, because it does not exist in the index."); } logger.info("deleteText(" + tid + ", " + lid + ") -> OK"); if (isPersistent) { exportJson(index.values()); } } public static TagModel getTagsModel(String tagId) { // TODO Auto-generated method stub return null; } }
package krasa.grepconsole.stats; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.HyperlinkAdapter; import com.intellij.ui.HyperlinkLabel; import com.intellij.ui.JBColor; import com.intellij.util.CommonProcessors; import com.intellij.util.ui.UIUtil; import krasa.grepconsole.filter.HighlightingFilter; import krasa.grepconsole.filter.support.GrepProcessor; import krasa.grepconsole.model.GrepColor; import krasa.grepconsole.model.GrepExpressionItem; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.HyperlinkEvent; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import java.util.TimerTask; /** * @author Vojtech Krasa */ public class StatisticsConsolePanel extends JPanel implements Disposable { private List<Pair<JLabel, GrepProcessor>> pairs = new ArrayList<>(); private java.util.Timer timer; private final JPanel jPanel; private HighlightingFilter highlightingFilter; private ConsoleViewImpl consoleView; public StatisticsConsolePanel(HighlightingFilter filter, ConsoleViewImpl consoleView) { super(new BorderLayout()); this.highlightingFilter = filter; this.consoleView = consoleView; setBorder(new EmptyBorder(0, 0, 0, 0)); final FlowLayout layout = new FlowLayout(); layout.setVgap(-4); layout.setHgap(0); jPanel = new JPanel(layout); jPanel.setBackground(getBackground()); add(jPanel, BorderLayout.WEST); init(); startUpdater(); } public void reset() { pairs.clear(); jPanel.removeAll(); init(); revalidate(); repaint(); } public Project getProject() { return highlightingFilter.getProject(); } private void init() { final List<GrepProcessor> grepProcessors = highlightingFilter.getGrepProcessors(); for (GrepProcessor grepProcessor : grepProcessors) { if (grepProcessor.getGrepExpressionItem().isShowCountInConsole()) { add(grepProcessor, new MyMouseInputAdapter(grepProcessor)); } } addButtons(); } public void addButtons() { jPanel.add(createActionLabel("Reset", new Runnable() { @Override public void run() { StatisticsManager.clearCount(highlightingFilter); reset(); } })); jPanel.add(createActionLabel("Hide", new Runnable() { @Override public void run() { StatisticsConsolePanel.this.dispose(); } })); } public void add(GrepProcessor processor, final MouseInputAdapter mouseInputAdapter) { jPanel.add(createCounterPanel(processor, mouseInputAdapter)); } private JPanel createCounterPanel(GrepProcessor processor, final MouseInputAdapter mouseInputAdapter) { GrepColor backgroundColor = processor.getGrepExpressionItem().getStyle().getBackgroundColor(); GrepColor foregroundColor = processor.getGrepExpressionItem().getStyle().getForegroundColor(); final JPanel panel = new JPanel(new FlowLayout()); panel.setBackground(getBackground()); final JLabel label = new JLabel("0"); label.setForeground(JBColor.BLACK); pairs.add(Pair.create(label, processor)); final krasa.grepconsole.stats.common.ColorPanel color = new krasa.grepconsole.stats.common.ColorPanel( processor.getGrepExpressionItem().getGrepExpression()); color.setSelectedColor(backgroundColor.getColorAsAWT()); color.setBorderColor(foregroundColor.getColorAsAWT()); color.setBackground(getBackground()); color.addMouseListener(mouseInputAdapter); panel.addMouseListener(mouseInputAdapter); panel.add(color); panel.add(label); return panel; } @Override public Color getBackground() { Color color = EditorColorsManager.getInstance().getGlobalScheme().getColor( EditorColors.NOTIFICATION_BACKGROUND); return color == null ? UIUtil.getToolTipBackground() : color; } private HyperlinkLabel createActionLabel(final String text, final Runnable action) { HyperlinkLabel label = new HyperlinkLabel(text, JBColor.BLACK, getBackground(), JBColor.BLUE); label.addHyperlinkListener(new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { action.run(); } }); return label; } public boolean hasItems() { return !pairs.isEmpty(); } public void startUpdater() { timer = new java.util.Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (!pairs.isEmpty()) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { for (Pair<JLabel, GrepProcessor> pair : pairs) { pair.getFirst().setText(String.valueOf(pair.second.getMatches())); } } }); } } }, 100, 100); } private void cancelTimer() { if (timer != null) { timer.cancel(); timer = null; } } @Override public void dispose() { cancelTimer(); consoleView = null; Container parent = getParent(); if (parent != null) { parent.remove(this); if (parent instanceof JPanel) { ((JPanel) parent).revalidate(); } } } private class MyMouseInputAdapter extends MouseInputAdapter { private final GrepProcessor grepProcessor; private final GrepExpressionItem grepExpressionItem; public MyMouseInputAdapter(GrepProcessor grepProcessor) { this.grepProcessor = grepProcessor; this.grepExpressionItem = grepProcessor.getGrepExpressionItem(); } @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { Editor myEditor = consoleView.getEditor(); MarkupModelEx model = (MarkupModelEx) myEditor.getMarkupModel(); CommonProcessors.CollectProcessor<RangeHighlighter> processor = new CommonProcessors.CollectProcessor<RangeHighlighter>() { @Override protected boolean accept(RangeHighlighter rangeHighlighter) { if (rangeHighlighter.getLayer() == HighlighterLayer.CONSOLE_FILTER) { //won't work when multiple processorItems combine attributes return rangeHighlighter.getTextAttributes() == grepExpressionItem.getConsoleViewContentType(null).getAttributes(); } return false; } }; int to = myEditor.getCaretModel().getPrimaryCaret().getOffset() - 1; model.processRangeHighlightersOverlappingWith(0, to, processor); List<RangeHighlighter> highlighters = (List<RangeHighlighter>) processor.getResults(); if (highlighters.isEmpty() && to + 1 < myEditor.getDocument().getTextLength()) { model.processRangeHighlightersOverlappingWith(to, myEditor.getDocument().getTextLength(), processor); highlighters = (List<RangeHighlighter>) processor.getResults(); } if (!highlighters.isEmpty()) { RangeHighlighter rangeHighlighter = highlighters.get(highlighters.size() - 1); myEditor.getCaretModel().getPrimaryCaret().moveToOffset(rangeHighlighter.getStartOffset()); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true)); } } } } }
package mathsquared.resultswizard2; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; /** * @author MathSquared * */ public class ArrayUtils { /** * Creates a deep copy of a multi-dimensional array, copying all sub-arrays of the array (but not the elements themselves). * * @param toCopy the multi-dimensional array to copy * @return a copy of the array, or null if <code>toCopy</code> is null */ // HASHTAG UNCHECKED CASTS @SuppressWarnings("unchecked") public static <T> T[][] deepCopyOf (T[][] toCopy) { // Null handling; null is a copy of null if (toCopy == null) { return null; } // Instantiate a generic array Class<T[]> type = (Class<T[]>) toCopy.getClass().getComponentType(); T[][] copied = (T[][]) Array.newInstance(type, toCopy.length); // If a two-dimensional array, use Arrays.copyOf; otherwise, recurse if (!(toCopy instanceof Object[][][])) { // not 3-D; by parameter, must be 2-D for (int i = 0; i < toCopy.length; i++) { copied[i] = Arrays.copyOf(toCopy[i], toCopy[i].length); } } else { // 3-D or above for (int i = 0; i < toCopy.length; i++) { copied[i] = (T[]) deepCopyOf((Object[][]) toCopy[i]); } } return copied; } /** * Checks that all ties are represented validly. * * <p> * For every sub-array of a result array (which represents a tie), if the sub-array contains more than one element, places should be skipped in accordance. This corresponds to normal practice; for example, if two people tie for first place, the next place awarded is third place (and the second-place array should be null or empty). * </p> * * <p> * For a parameter of null, this method returns true. * </p> * * @param results the results array whose integrity to check * @return true if the array correctly skips places for ties; false otherwise */ public static boolean checkTies (String[][] results) { // An empty array is structured correctly, since there are no unstructured elements if (results == null) { return true; } /* * Implementation: * * The algorithm keeps track of the amount of results that have been seen so far, where a "result" is one String. * * For each sub-array of the input array, the algorithm adds subArr.length - 1 to an internal tracking variable. * * If this variable is non-zero, it means that there was a tie previously, and the next few places should be skipped with null. * * If this variable is zero, it means that there have been no ties--or all were accounted for--so the next array should have elements. */ int num = 0; // tracking variable mentioned above for (String[] x : results) { // num never decreases by more than 1 each turn, and can never decrease if it is 0, so check for num < 0 is unnecessary assert (num >= 0); if (num == 0 && (x == null || x.length == 0)) { return false; } if (num > 0 && x != null && x.length != 0) { return false; } num += (x == null) ? -1 : x.length - 1; } // no problems; num does not need to be 0 in case of ties for last place return true; } /** * Checks that the structure of two arrays is the same. That is: * * <ul> * <li><code>a.length == b.length</code></li> * <li>For any integer <code>i</code>, <code>a[i]</code> is an array iff <code>b[i]</code> is an array</li> * <li>For any integer <code>i</code>, if <code>a[i]</code> and <code>b[i]</code> are arrays, the first two statements are recursively valid for them as well</li> * </ul> * * <p> * If one of the arrays is null, this method returns true iff both are null. * </p> * * @param a the first array to check * @param b the second array to check * @return true if the arrays have the same structure as defined above, false otherwise */ public static boolean checkStructureSame (Object[] a, Object[] b) { // Null handling; two nulls are structured the same, but a null and non-null are not if (a == null && b == null) { return true; } if (a == null ^ b == null) { return false; } if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if (a[i] instanceof Object[] && b[i] instanceof Object[]) { if (!checkStructureSame((Object[]) a[i], (Object[]) b[i])) { return false; } } // Not generic, so no enforcement on same type...might have one be an array of arrays and the other not be if (a[i] instanceof Object[] ^ b[i] instanceof Object[]) { return false; } } // no problems return true; } /** * Returns an array of the lengths of the sub-arrays of a given array. * * <p> * That is, returns an array <code>ret</code> such that: * </p> * * <ul> * <li><code>ret.length == arr.length</code>, and</li> * <li>for all integers <code>i</code> where <code>0 &lt; i &lt; arr.length</code>, <code>ret[i] = arr[i].length</code>. The length of a null array is defined to be 0.</li> * </ul> * * @param arr a two-or-more-dimensional array * @return a length array as described above, or null if <code>arr</code> is null */ public static int[] lengthArray (Object[][] arr) { if (arr == null) { return null; } int[] ret = new int[arr.length]; for (int i = 0; i < arr.length; i++) { ret[i] = (arr[i] != null) ? arr[i].length : 0; // null array has 0 length } return ret; } public static int[] condensedLengthArray (Object[][] arr) { // TODO Check ties return condensedLengthArray(lengthArray(arr)); } public static int[] condensedLengthArray (int[] lengthArray) { ArrayList<Integer> ret = new ArrayList<Integer>(); for (int i = 0; i < lengthArray.length; i++) { int x = lengthArray[i]; if (x == 0) { // there should be no zeroes except to skip places throw new IllegalArgumentException("Improperly formatted length array: zero at " + i); } if (x < 0) { throw new IllegalArgumentException("Invalid length array: negative at " + i); } ret.add(x); int initI = i; // Skip places, checking to ensure that each one is 0--intentionally updates the outer loop counter for (; i < initI + x - 1 && i < lengthArray.length; i++) { if (lengthArray[i] < 0) { throw new IllegalArgumentException("Invalid length array: negative at " + i); } if (lengthArray[i] > 0) { throw new IllegalArgumentException("Improperly formatted length array: nonzero at " + i); } } } // Unbox the ArrayList (it would be easier if it was automatic, but I understand the performance hit array autounboxing would cause) Integer[] pending = ret.toArray(new Integer[0]); int[] retArr = new int[pending.length]; for (int i = 0; i < pending.length; i++) { retArr[i] = pending[i]; } return retArr; } }
package graph; import graph.doublyLinkedList.DLLNode; import graph.doublyLinkedList.DoublyLinkedList; import graph.doublyLinkedList.NodeIterator; import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Graph <E,T> { // Graph content private DoublyLinkedList<Vertex <E,T>> vertexList; private DoublyLinkedList<Edge<E,T>> edgeList; // Graph options private boolean directed; private boolean isCyclic; private boolean isConnected; private int connectedComponents; // Unique id for each vertex in a graph. In a cloned graph, cloned vertices will have the same id private int unique_id = 0; /** * Constructor * @param directed true if the graph is directed, false if undirected */ public Graph(boolean directed) { vertexList = new DoublyLinkedList<Vertex<E,T>>(); edgeList = new DoublyLinkedList<Edge<E,T>>(); this.directed = directed; } /** * Add vertex to the graph * @param data * @return Added vertex */ public Vertex<E,T> addVertex(E data){ return addVertex(data, unique_id++); } /** * Add Edge between two vertices * @param v1 * @param v2 * @param label * @param weight * @return Array of 2 edges if the graph is undirected, array of 1 edge if the graph is directed */ public Edge<E,T>[] addEdge(Vertex<E,T> v1, Vertex<E,T> v2, T label, double weight){ Edge<E,T> edges[] = new Edge[directed ? 1 : 2]; // Create the first edge from v1 to v2 and set its configuration edges[0] = new Edge<E,T>(v1, v2); edges[0].setLabel(label); edges[0].setWeight(weight); edges[0].setPosition(edgeList.add(edges[0])); // If graph is undirected, create an edge in the opposite direction if(!directed){ // Create the second edge from v2 to v1 and set its configuration edges[1] = new Edge<E,T>(v2, v1); edges[1].setLabel(label); edges[1].setWeight(weight); edges[1].setPosition(edgeList.add(edges[1])); } return edges; } /** * Add Edge between two vertices * @param v1 * @param v2 * @return Array of 2 edges if the graph is undirected, array of 1 edge if the graph is directed */ public Edge<E,T>[] addEdge(Vertex<E,T> v1, Vertex<E,T> v2){ return addEdge(v1, v2, null, 0.0); } /** * Remove vertex * @param vertex */ public void removeVertex(Vertex<E,T> vertex){ // Remove outgoing edges & trigger NodeIterator<Edge<E,T>> iterOutEdges = vertex.getOutEdges(); while(iterOutEdges.hasNext()){ Edge<E,T> currentE = iterOutEdges.next(); Vertex<E,T> vTo = currentE.getV2(); // Remove edge from inEdge of V2 vTo.removeInEdge(currentE.getIncidentPositionV2()); // Remove edge from the graph content edgeList.remove(currentE.getPosition()); } // Remove ingoing edges & trigger NodeIterator<Edge<E,T>> iterInEdges = vertex.getInEdges(); while(iterInEdges.hasNext()){ Edge<E,T> currentE = iterInEdges.next(); Vertex<E,T> vFrom = currentE.getV1(); // Remove edge from outEdge of V1 vFrom.removeOutEdge(currentE.getIncidentPositionV1()); // Remove edge from the graph content edgeList.remove(currentE.getPosition()); } // Remove vertex vertexList.remove(vertex.getPosition()); } /** * Remove edge * @param edge */ public void removeEdge(Edge<E,T> edge){ edge.getV1().removeOutEdge(edge.getIncidentPositionV1()); edge.getV2().removeInEdge(edge.getIncidentPositionV2()); edgeList.remove(edge.getPosition()); } /** * Breadth-First-Search starting from a specific vertex * @return Array of vertices traversed by BFS */ public Vertex<E,T>[] BFS(Vertex<E,T> vertex){ // Mark all vertices as unvisited NodeIterator<Vertex<E,T>> iterV = vertices(); while(iterV.hasNext()) iterV.next().setStatus(Vertex.UNVISITED); // Mark all edges as undiscovered NodeIterator<Edge<E,T>> iterE = edges(); while(iterE.hasNext()) iterE.next().setStatus(Edge.UNDISCOVERED); // Create the list to store the vertices DoublyLinkedList<Vertex<E,T>> BFS_list = new DoublyLinkedList<>(); // Add the starting vertex and mark it as visiting Queue<Vertex<E,T>> q = new LinkedList<Vertex<E,T>>(); q.add(vertex); vertex.setStatus(Vertex.VISITING); while(!q.isEmpty()){ // Remove a vertex from the queue and mark it as visited Vertex<E,T> polled = q.poll(); BFS_list.add(polled); polled.setStatus(Vertex.VISITED); // Iterator on all neighbors of the removed vertex and add them to the queue NodeIterator<Edge<E,T>> incidentEdges = polled.getOutEdges(); while(incidentEdges.hasNext()){ Edge<E,T> edge = incidentEdges.next(); Vertex<E,T> oppositeVertex = edge.getV2(); // If neighbor is not already visited, put it in the queue if(oppositeVertex.getStatus() == Vertex.UNVISITED){ // Mark edge between the removed vertex and the current neighbor as discovered edge.setStatus(Edge.DISCOVERED); oppositeVertex.setStatus(Vertex.VISITING); q.offer(oppositeVertex); // If neighbor has already been visited, don't put it in the queue }else{ // Mark edge as cross if undiscovered if(edge.getStatus() == Edge.UNDISCOVERED) edge.setStatus(Edge.CROSS); } } } NodeIterator<Vertex<E,T>> BFS_iter = BFS_list.iterator(); Vertex<E,T> BFS[] = new Vertex[BFS_iter.size()]; int index = 0; while(BFS_iter.hasNext()) BFS[index++] = BFS_iter.next(); return BFS; } /** * Breadth-First-Search * @return Array of vertices traversed by BFS */ public Vertex<E,T>[] BFS(){ Vertex<E,T>[] BFS = new Vertex[vertexList.size()]; int index = 0; // Mark all vertices as unvisited NodeIterator<Vertex<E,T>> iterV = vertices(); while(iterV.hasNext()) iterV.next().setStatus(Vertex.UNVISITED); // Mark all edges as undiscovered NodeIterator<Edge<E,T>> iterE = edges(); while(iterE.hasNext()) iterE.next().setStatus(Edge.UNDISCOVERED); // Start BFS iterV = vertices(); while(iterV.hasNext()){ Vertex<E,T> current = iterV.next(); if(current.getStatus() == Vertex.UNVISITED){ // Add the starting vertex and mark it as visiting Queue<Vertex<E,T>> q = new LinkedList<Vertex<E,T>>(); q.add(current); current.setStatus(Vertex.VISITING); while(!q.isEmpty()){ // Remove a vertex from the queue and mark it as visited Vertex<E,T> polled = q.poll(); BFS[index++] = polled; polled.setStatus(Vertex.VISITED); // Iterator on all neighbors of the removed vertex and add them to the queue NodeIterator<Edge<E,T>> incidentEdges = polled.getOutEdges(); while(incidentEdges.hasNext()){ Edge<E,T> edge = incidentEdges.next(); Vertex<E,T> oppositeVertex = edge.getV2(); // If neighbor is not already visited, put it in the queue if(oppositeVertex.getStatus() == Vertex.UNVISITED){ // Mark edge between the removed vertex and the current neighbor as discovered edge.setStatus(Edge.DISCOVERED); oppositeVertex.setStatus(Vertex.VISITING); q.offer(oppositeVertex); // If neighbor has already been visited, don't put it in the queue }else{ // Mark edge as cross if undiscovered if(edge.getStatus() == Edge.UNDISCOVERED) edge.setStatus(Edge.CROSS); } } } } } return BFS; } /** * Depth-First-Search * @return Array of vertices traversed by DFS */ public Vertex<E,T>[] DFS(){ Vertex<E,T>[] DFS = new Vertex[vertexList.size()]; int index[] = {0}; // Configure Graph options this.connectedComponents = 0; this.isCyclic = false; // Mark all vertices as unvisited and uncolored NodeIterator<Vertex<E,T>> iterV = vertices(); while(iterV.hasNext()){ Vertex<E,T> currentV = iterV.next(); currentV.setStatus(Vertex.UNVISITED); currentV.setColor(Vertex.UNCOLORED); } // Mark all edges as undiscovered NodeIterator<Edge<E,T>> iterE = edges(); while(iterE.hasNext()) iterE.next().setStatus(Edge.UNDISCOVERED); // Start DFS iterV = vertices(); while(iterV.hasNext()){ Vertex<E,T> current = iterV.next(); if(current.getStatus() == Vertex.UNVISITED){ // +1 disconnected graph, trigger connection detection this.connectedComponents++; this.isConnected = this.connectedComponents == 1; DFS(current, DFS, index); } } return DFS; } /** * Recursive DFS that generates the content of DFS[] * @param v * @param DFS * @param index */ private void DFS(Vertex<E,T> v, Vertex<E,T>[] DFS, int[] index){ // Color all vertices with the same color for each vertex start ((v0-> v1) <- v2) [for DiGraph] v.setColor(connectedComponents); v.setStatus(Vertex.VISITING); DFS[index[0]++] = v; // Iterate on all neighbors of the current vertex NodeIterator<Edge<E,T>> incidentEdges = v.getOutEdges(); while(incidentEdges.hasNext()){ Edge<E,T> edge = incidentEdges.next(); Vertex<E,T> oppositeVertex = edge.getV2(); // Recur on neighbor if not visited if(oppositeVertex.getStatus() == Vertex.UNVISITED){ edge.setStatus(Edge.DISCOVERED); oppositeVertex.setStatus(Vertex.VISITING); DFS(oppositeVertex, DFS,index); }else{ // Checks if the undirected/directed graph is cyclic if( (!directed && oppositeVertex.getStatus() == Vertex.VISITED) || (directed && oppositeVertex.getStatus() == Vertex.VISITING && v.getColor() == oppositeVertex.getColor()) // Third condition is for DiGraph (Check earlier this method...) ){ isCyclic = true; } /// Mark edge as cross if the undiscovered if(edge.getStatus() == Edge.UNDISCOVERED) edge.setStatus(Edge.CROSS); } } // Mark vertex as visited if more neighbors needs to be visited v.setStatus(Vertex.VISITED); } /** * Depth-First-Search from a specific vertex * @return Array of vertices traversed by DFS */ public Vertex<E,T>[] DFS(Vertex<E,T> vertex){ // Mark all vertices as unvisited and uncolored NodeIterator<Vertex<E,T>> iterV = vertices(); while(iterV.hasNext()){ Vertex<E,T> currentV = iterV.next(); currentV.setStatus(Vertex.UNVISITED); currentV.setColor(Vertex.UNCOLORED); } // Mark all edges as undiscovered NodeIterator<Edge<E,T>> iterE = edges(); while(iterE.hasNext()) iterE.next().setStatus(Edge.UNDISCOVERED); // Create the list to store the vertices DoublyLinkedList<Vertex<E,T>> DFS_list = new DoublyLinkedList<>(); // Populate the list DFS(vertex, DFS_list); // Create the return array NodeIterator<Vertex<E,T>> iter_DFS = DFS_list.iterator(); Vertex<E,T> DFS[] = new Vertex[iter_DFS.size()]; int index = 0; while(iter_DFS.hasNext()) DFS[index++] = iter_DFS.next(); return DFS; } /** * Recursive DFS that generates the content of DFS_list * @param vertex * @param DFS_list */ private void DFS(Vertex<E,T> vertex, DoublyLinkedList<Vertex<E,T>> DFS_list){ vertex.setStatus(Vertex.VISITING); DFS_list.add(vertex); // Iterate on all neighbors of the current vertex NodeIterator<Edge<E,T>> incidentEdges = vertex.getOutEdges(); while(incidentEdges.hasNext()){ Edge<E,T> edge = incidentEdges.next(); Vertex<E,T> oppositeVertex = edge.getV2(); // Recur on neighbor if not visited if(oppositeVertex.getStatus() == Vertex.UNVISITED){ edge.setStatus(Edge.DISCOVERED); oppositeVertex.setStatus(Vertex.VISITING); DFS(oppositeVertex, DFS_list); }else{ /// Mark edge as cross if the undiscovered if(edge.getStatus() == Edge.UNDISCOVERED) edge.setStatus(Edge.CROSS); } } // Mark vertex as visited if more neighbors needs to be visited vertex.setStatus(Vertex.VISITED); } /** * Get an iterator for the list of vertices * @return NodeIterator of vertices */ public NodeIterator<Vertex<E,T>> vertices() { return vertexList.iterator(); } /** * Get an iterator for the list of edges * @return NodeIterator of edges */ public NodeIterator<Edge<E,T>> edges() { return edgeList.iterator(); } /** * Get an array of the list of vertices * @return Array of vertices */ public Vertex<E,T>[] vertices_array(){ Vertex<E,T>[] tmp = new Vertex[vertexList.size()]; NodeIterator<Vertex<E,T>> iter = vertices(); int index = 0; while(iter.hasNext()) tmp[index++] = iter.next(); return tmp; } /** * Get an array of the list of vertices * @return Array of vertices */ public Edge<E,T>[] edges_array(){ Edge<E,T>[] tmp = new Edge[edgeList.size()]; NodeIterator<Edge<E,T>> iter = edges(); int index = 0; while(iter.hasNext()) tmp[index++] = iter.next(); return tmp; } /** * Checks if the graph is directed or not * @return boolean */ public boolean isDirected() { return directed; } /** * Checks if the graph contains a cycle * @return boolean */ public boolean isCyclic(){ DFS(); return isCyclic; } /** * Checks if the graph is connected * @return boolean */ public boolean isConnected(){ if(directed) BFS_DiGraph_helper(); else DFS(); return isConnected; } /** * Gives the number of connected components * @return connected components */ public int connectedComponents(){ if(directed) BFS_DiGraph_helper(); else DFS(); return connectedComponents; } /** * Create the shortest path from a vertex to all other vertices * @param v Starting vertex */ public void dijkstra(Vertex<E,T> v){ // Mark all vertices as unvisited and reset Dijkstra options NodeIterator<Vertex<E,T>> iterV = vertices(); while(iterV.hasNext()){ Vertex<E,T> currentV = iterV.next(); currentV.setStatus(Vertex.UNVISITED); currentV.setDijkstra_value(Double.MAX_VALUE); currentV.setDijkstra_parent(null); } // Mark all edges as undiscovered NodeIterator<Edge<E,T>> iterE = edges(); while(iterE.hasNext()) iterE.next().setStatus(Edge.UNDISCOVERED); // Mark the starting vertex v.setDijkstra_value(0); // Create the Priority Queue (Using a heap) PriorityQueue<Vertex<E,T>> pq = new PriorityQueue<>(); // Start from the starting vertex by putting it in the Priority queue pq.offer(v); v.setStatus(Vertex.VISITING); v.setDijkstra_parent(v); while(!pq.isEmpty()){ // Remove the vertex with minimum Dijkstra value Vertex<E,T> polled = pq.poll(); v.setStatus(Vertex.VISITED); NodeIterator<Edge<E,T>> incidentEdges = polled.getOutEdges(); // Put all the neighbors of the removed vertex in the Priority queue and adjust their Dijkstra value and parent while(incidentEdges.hasNext()){ Edge<E,T> edge = incidentEdges.next(); Vertex<E,T> oppositeVertex = edge.getV2(); double pathCost = edge.getWeight() + polled.getDijkstra_value(); // If the neighbor has not been visited, mark it visiting and adjust its configuration if(oppositeVertex.getStatus() == Vertex.UNVISITED){ oppositeVertex.setDijkstra_value(pathCost); oppositeVertex.setDijkstra_edge(edge); edge.setStatus(Edge.DISCOVERED); oppositeVertex.setStatus(Vertex.VISITING); oppositeVertex.setDijkstra_parent(polled); pq.offer(oppositeVertex); // If the neighbor is still in the priority queue, check for minimum path cost, adjust if the cost can be reduced }else if(oppositeVertex.getStatus() == Vertex.VISITING){ if(oppositeVertex.getDijkstra_value() > pathCost){ oppositeVertex.setDijkstra_value(pathCost); edge.setStatus(Edge.DISCOVERED); oppositeVertex.setDijkstra_parent(polled); oppositeVertex.getDijkstra_edge().setStatus(Edge.FORWARD); // Mark previous edge as FORWARD oppositeVertex.setDijkstra_edge(edge); // Update edge that makes it shortest path } } } } } /** * Get the shortest path from one vertex to another * @param vFrom * @param vTo * @return Array of shortest edges to go from vFrom to vTo */ public Edge<E,T>[] dijkstra(Vertex<E,T> vFrom, Vertex<E,T> vTo){ this.dijkstra(vFrom); Stack<Edge<E,T>> path = new Stack<>(); Vertex<E,T> current = vTo; // Push the path in the stack in backward direction while(current.getDijkstra_edge() != null){ path.push(current.getDijkstra_edge()); current = current.getDijkstra_parent(); } // Store path, in the correct direction, in an array Edge<E,T>[] edges = new Edge[path.size()]; int index = 0; while(!path.isEmpty()) edges[index++] = path.pop(); return edges; } /** * Checks if two vertices are adjacent * @param v1 From * @param v2 To * @return boolean */ public boolean areAdjacent(Vertex<E,T> v1, Vertex<E,T> v2){ // If directed graph or size of v1 out edges < size of v2 out edges Vertex<E,T> v = directed || (v1.getOutEdges().size() < v2.getOutEdges().size()) ? v1 : v2; NodeIterator<Edge<E,T>> iterOutE = v.getOutEdges(); while(iterOutE.hasNext()) if( (v == v1 && iterOutE.next().getV2() == v2) || (v == v2 && iterOutE.next().getV2() == v1) ) return true; return false; } public void transitiveClosure(){ Vertex<E,T> vertices[] = this.vertices_array(); for(int k = 0; k < vertices.length; k++){ for(int i = 0; i < vertices.length; i++){ // If i = k, then skip if(i == k) continue; // If i and k are adjacent, check for k and j if(areAdjacent(vertices[i], vertices[k])){ for(int j = 0; j < vertices.length; j++){ // If j = i or j = k, then skip if(j == i || j == k) continue; // If k and j are adjacent AND i and j are not adjacent, create an edge between i and j if(areAdjacent(vertices[k], vertices[j]) && !areAdjacent(vertices[i], vertices[j])) this.addEdge(vertices[i],vertices[j], null, 0.0); } } } } } /** * Clone vertices and edges, but does not clone the data of the vertex * @return cloned graph */ public Graph<E,T> clone(){ // Create new graph, (To avoid edge duplication the graph is marked directed, but adjusted at the end) Graph<E,T> graph = new Graph<E,T>(true); // Clone Vertices NodeIterator<Vertex<E,T>> iterV = vertexList.iterator(); while(iterV.hasNext()){ Vertex<E,T> vertex = iterV.next(); graph.addVertex(vertex.getData(), vertex.getID()); } // Store vertices in an array so we can clone using unique id and indices Vertex<E,T> vertices[] = graph.vertices_array(); // Clone Edges NodeIterator<Edge<E,T>> iterE = edgeList.iterator(); while(iterE.hasNext()){ Edge<E,T> currentE = iterE.next(); // Binary search is used because the ID are sorted in ascending order // Note: Searching for vertices is required because any vertex can be removed, and gaps in IDs will be formed Vertex<E,T> v1 = vertices[getIndexOfVertexByID(vertices, currentE.getV1().getID())]; Vertex<E,T> v2 = vertices[getIndexOfVertexByID(vertices, currentE.getV2().getID())]; graph.addEdge(v1, v2, currentE.getLabel(), currentE.getWeight()); } // Adjust the directed/undirected graph option and unique id counter graph.directed = directed; graph.unique_id = unique_id; return graph; } /** * Gives all the vertices and edges that form this graph * @return String */ public String toString(){ String output = "Vertices:\n"; for(Vertex<E,T> v : vertices_array()) output += String.format("%s ", v.toString()); output += "\n\nEdges:\n"; for(Edge<E,T> e : edges_array()){ output += String.format("%s\n", e.toString()); } return output; } /** * Read graph from input * @param fileName * @param directed * @return Graph created * @throws FileNotFoundException */ public static Graph<String,String> inParser (String fileName, boolean directed) throws FileNotFoundException{ Graph<String,String> graph = new Graph<String,String>(directed); Scanner scan = new Scanner(new File(fileName)); String readLine; Pattern pattern; Matcher matcher; readLine = scan.nextLine(); pattern = Pattern.compile("size\\s*=\\s*(\\d+)"); matcher = pattern.matcher(readLine); matcher.find(); Vertex<String,String> vertices[] = new Vertex[Integer.parseInt(matcher.group(1))]; while(!(readLine = scan.nextLine()).equals(";") ){ pattern = Pattern.compile("([^0-9]*)\\s*(\\d+)\\s*=\\s*(.*)"); matcher = pattern.matcher(readLine); matcher.find(); if(matcher.group(1) == null || matcher.group(1).isEmpty()){ vertices[Integer.parseInt(matcher.group(2))] = graph.addVertex(matcher.group(3)); }else if(matcher.group(1).trim().equals("//") || matcher.group(1).trim().equals(" continue; }else{ throw new InputMismatchException(); } } while(!(readLine = scan.nextLine()).equals(";") ){ pattern = Pattern.compile("(.*)\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(,\\s*(\\d+|\\d+\\.\\d+)\\s*)?\\)(\\s*=\\s*(.*))?"); matcher = pattern.matcher(readLine); matcher.find(); if(matcher.group(1) == null || matcher.group(1).isEmpty()){ double weight = 0.0; int v1Index = Integer.parseInt(matcher.group(2)); int v2Index = Integer.parseInt(matcher.group(3)); if(matcher.group(5) != null) weight = Double.parseDouble(matcher.group(5)); String label = matcher.group(7); graph.addEdge(vertices[v1Index], vertices[v2Index], label, weight); }else if(matcher.group(1).trim().equals("//") || matcher.group(1).trim().equals(" continue; }else{ throw new InputMismatchException(); } } return graph; } /////////////////////////////// HELPER //////////////////////////////// /** * BFS for detecting connected components and is connected in DiGraphs * Idea is to consider the DiGraph as UnDiGraph by concatenating the in and out edges */ private Vertex<E,T>[] BFS_DiGraph_helper() { Vertex<E,T>[] BFS = new Vertex[vertexList.size()]; int index = 0; // Configure DiGraph options this.connectedComponents = 0; // Mark all vertices as unvisited NodeIterator<Vertex<E,T>> iterV = vertices(); while (iterV.hasNext()) iterV.next().setStatus(Vertex.UNVISITED); // Mark all edges as undiscovered NodeIterator<Edge<E,T>> iterE = edges(); while (iterE.hasNext()) iterE.next().setStatus(Edge.UNDISCOVERED); // Start BFS iterV = vertices(); while (iterV.hasNext()) { Vertex<E,T> current = iterV.next(); if (current.getStatus() == Vertex.UNVISITED) { // +1 disconnected graph, trigger connection detection this.connectedComponents++; this.isConnected = this.connectedComponents == 1; Queue<Vertex<E,T>> q = new LinkedList<Vertex<E,T>>(); q.add(current); current.setStatus(Vertex.VISITING); while (!q.isEmpty()) { Vertex<E,T> polled = q.poll(); BFS[index++] = polled; polled.setStatus(Vertex.VISITED); NodeIterator<Edge<E,T>> inOutEdges = polled.getOutEdges().concatenate(polled.getInEdges()); while (inOutEdges.hasNext()) { Edge<E,T> edge = inOutEdges.next(); Vertex<E,T> oppositeVertex = edge.getOpposite(polled); if (oppositeVertex.getStatus() == Vertex.UNVISITED) { edge.setStatus(Edge.DISCOVERED); oppositeVertex.setStatus(Vertex.VISITING); q.offer(oppositeVertex); } else { if (edge.getStatus() == Edge.UNDISCOVERED) edge.setStatus(Edge.CROSS); } } } } } return BFS; } /** * Binary search for finding the index of a vertex in an array of vertices using the vertex unique id * @param array * @param target * @return index of target vertex or -1 if vertex not found */ public int getIndexOfVertexByID(Vertex<E,T>[] vertices, int id){ int left = 0; int right = vertices.length-1; int mid; while(left <= right){ mid = (left + right) / 2; if(vertices[mid].getID() == id) return mid; if(vertices[mid].getID() < id) left = mid + 1; else right = mid - 1; } return -1; } /** * Add vertex to the graph with custom ID * Private to avoid possible conflict if used manually * @param data * @return Vertex */ private Vertex<E,T> addVertex(E data, int id){ Vertex<E,T> vertex = new Vertex<E,T>(data, id); DLLNode<Vertex<E,T>> node = vertexList.add(vertex); vertex.setPosition(node); return vertex; } }
package ar.glyphsets; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import ar.GlyphSet; import ar.Util; /**Quad tree where items appear in each node that they touch (e.g., multi-homed). * Can split an existing node into sub-nodes or move "up" and make the root a sub-node with new sibblings/parent. * No items are held in intermediate nodes * * There are four types of nodes: * ** RootHolder is a proxy for a root node, * but enables the bounds of the tree to expand without the host program knowing. * ** InnerNode is a node that has no items in it, but has quadrants below it that may have items * ** LeafNode is a node that may have items but also may have one more set of nodes beneath it. * The items directly held by the leaf nodes are those that touch multiple of its children. * ** LeafQuad is a node that may have items but no children. All items held in a LeafQuad are * entirely contained by that LeafQuad. * * The LeafNode vs. LeafQuad split is made so the decision to further divide the tree * can be flexible and efficient. A LeafNode may only have LeafQuads as its children. * * **/ public abstract class DynamicQuadTree implements GlyphSet { public static double MIN_DIM = .0001d; public static double CROSS_LOAD_FACTOR = .25; public static int LOADING = 10; public static int NW = 0; public static int NE = 1; public static int SW = 2; public static int SE = 3; /**Structure to represent the bounds of the sub-quardants of a node**/ private static final class Subs { public final Rectangle2D[] quads = new Rectangle2D[4]; public Subs (final Rectangle2D current) { double w = current.getWidth()/2; double h = current.getHeight()/2; quads[NW] = new Rectangle2D.Double(current.getX(), current.getY(),w,h); quads[NE] = new Rectangle2D.Double(current.getCenterX(), current.getY(), w,h); quads[SW] = new Rectangle2D.Double(current.getX(), current.getCenterY(), w,h); quads[SE] = new Rectangle2D.Double(current.getCenterX(), current.getCenterY(), w,h); } } /**How many items before exploring subdivisions.**/ protected final Rectangle2D concernBounds; public static DynamicQuadTree make() {return new DynamicQuadTree.RootHolder();} protected DynamicQuadTree(Rectangle2D concernBounds) { this.concernBounds = concernBounds; } /**What space is this node responsible for?**/ public Rectangle2D concernBounds() {return concernBounds;} /**Tight bounding of the items contained under this node. * Will always be equal to or smaller than concernBounds. * Where concernBounds is a statement of what may be, * bounds is a statement of what is.**/ public abstract Rectangle2D bounds(); /**Add an item to the node's sub-tree**/ public abstract void add(Glyph glyph); /**How many things are held in this sub-tree?**/ public int size() {return items().size();} /**What are the items of the sub-tree?**/ public Collection<Glyph> items() { Collection<Glyph> collector = new HashSet<Glyph>(); items(collector); return collector; } /**Efficiency method for collecting items.**/ protected abstract void items(Collection<Glyph> collector); /**What items in this sub-tree contain the passed point?**/ public Collection<Glyph> containing(Point2D p) { Collection<Glyph> collector2 = new ArrayList<Glyph>(); containing(p, collector2); return collector2; } /**Efficiency method for collecting items touching a point**/ protected abstract void containing(Point2D p, Collection<Glyph> collector); protected boolean doSplit() {return false;} /**Convert the tree to a string where indentation indicates depth in tree.**/ public abstract String toString(int indent); public String toString() {return toString(0);} protected static DynamicQuadTree addTo(DynamicQuadTree target, Glyph item) { target.add(item); if (target.doSplit()) { return new InnerNode((LeafNode) target); } else { return target; } } /**The root node does not actually hold an items, it is to faciliate the "up" direction splits. * A node of this type is always the initial node of the tree. Most operations are passed * through it to its only child.**/ private static final class RootHolder extends DynamicQuadTree { private DynamicQuadTree child; public RootHolder() { super(null); child = new LeafNode(new Rectangle2D.Double(0,0,0,0)); } public void add(Glyph glyph) { Rectangle2D b = glyph.shape.getBounds2D(); if (!child.concernBounds().contains(b)) { if (child instanceof LeafNode) { //If the root is a leaf, then the tree has no depth, so we feel free to expand the root //to fit the data until the loading limit has been reached Rectangle2D newBounds = Util.fullBounds(b, child.bounds()); DynamicQuadTree newChild = new LeafNode(newBounds, (LeafNode) child); this.child = newChild; } else { DynamicQuadTree c = child; while (!c.concernBounds.contains(b)) {c = growUp(c, b);} this.child = c; } } child = DynamicQuadTree.addTo(child, glyph); } private static final InnerNode growUp(DynamicQuadTree current, Rectangle2D toward) { Rectangle2D currentBounds = current.concernBounds(); if (toward.intersects(currentBounds)) { //If the root node is not a leaf, then make new sibblings/parent for the current root until it fits. //Growth is from the center-out, so the new siblings each get one quadrant from the current root //and have three quadrants that start out vacant. DynamicQuadTree.InnerNode iChild = (DynamicQuadTree.InnerNode) current; Rectangle2D newBounds = new Rectangle2D.Double( currentBounds.getX()-currentBounds.getWidth()/2.0d, currentBounds.getY()-currentBounds.getHeight()/2.0d, currentBounds.getWidth()*2, currentBounds.getHeight()*2); //The following checks prevent empty nodes from proliferating as you split up. //Leaf nodes in the old tree are rebounded for the new tree. //Non-leaf nodes are replaced with a quad of nodes InnerNode newChild = new InnerNode(newBounds); if (iChild.quads[NE] instanceof InnerNode) { newChild.quads[NE] =new InnerNode(newChild.quads[NE].concernBounds()); ((InnerNode) newChild.quads[NE]).quads[SW] = iChild.quads[NE]; } else if (!iChild.quads[NE].isEmpty()) { newChild.quads[NE] = new LeafNode(newChild.quads[NE].concernBounds(), (LeafNode) iChild.quads[NE]); } if (iChild.quads[NW] instanceof InnerNode) { newChild.quads[NW] = new InnerNode(newChild.quads[NW].concernBounds()); ((InnerNode) newChild.quads[NW]).quads[SE] = iChild.quads[NW]; } else if (!iChild.quads[NW].isEmpty()) { newChild.quads[NW] = new LeafNode(newChild.quads[NW].concernBounds(), (LeafNode) iChild.quads[NW]); } if (iChild.quads[SW] instanceof InnerNode) { newChild.quads[SW] = new InnerNode(newChild.quads[SW].concernBounds()); ((InnerNode) newChild.quads[SW]).quads[NE] = iChild.quads[SW]; } else if (!iChild.quads[SW].isEmpty()) { newChild.quads[SW] = new LeafNode(newChild.quads[SW].concernBounds(), (LeafNode) iChild.quads[SW]); } if (iChild.quads[SE] instanceof InnerNode) { newChild.quads[SE] = new InnerNode(newChild.quads[SE].concernBounds()); ((InnerNode) newChild.quads[SE]).quads[NW] = iChild.quads[SE]; } else if (!iChild.quads[SE].isEmpty()) { newChild.quads[SE] = new LeafNode(newChild.quads[SE].concernBounds(), (LeafNode) iChild.quads[SE]); } return newChild; } else { int outCode = currentBounds.outcode(toward.getX(), toward.getY()); if ((outCode & Rectangle2D.OUT_LEFT) == Rectangle2D.OUT_LEFT) { } else if ((outCode & Rectangle2D.OUT_RIGHT) == Rectangle2D.OUT_RIGHT) { } else if ((outCode & Rectangle2D.OUT_TOP) == Rectangle2D.OUT_TOP) { } else if ((outCode & Rectangle2D.OUT_BOTTOM) == Rectangle2D.OUT_BOTTOM) { } else {throw new RuntimeException("Growing up encountered unexpected out-code:" + outCode);} } } public boolean isEmpty() {return child.isEmpty();} public Rectangle2D concernBounds() {return child.concernBounds();} public Rectangle2D bounds() {return child.bounds();} public void items(Collection<Glyph> collector) {child.items(collector);} public void containing(Point2D p, Collection<Glyph> collector) {child.containing(p, collector);} public String toString(int indent) {return child.toString(indent);} } private static final class InnerNode extends DynamicQuadTree { private final DynamicQuadTree[] quads =new DynamicQuadTree[4]; /**Create a new InnerNode from an existing leaf node. * The quads of the leaf can be copied directly to the children of this node. * Only the spanning items of the leaf need to go through the regular add procedure. */ private InnerNode(LeafNode source) { this(source.concernBounds); for (int i=0; i<quads.length;i++) { for (Glyph g: source.quads[i].items) {quads[i].add(g);} } for (Glyph g:source.spanningItems) {add(g);} } private InnerNode(Rectangle2D concernBounds) { super(concernBounds); Subs subs = new Subs(concernBounds); for (int i=0; i< subs.quads.length; i++) { quads[i] = new DynamicQuadTree.LeafNode(subs.quads[i]); } } public void add(Glyph glyph) { boolean added = false; Rectangle2D glyphBounds = glyph.shape.getBounds2D(); for (int i=0; i<quads.length; i++) { DynamicQuadTree quad = quads[i]; if (quad.concernBounds.intersects(glyphBounds)) { quads[i] = addTo(quad, glyph); added = true; } } if (!added) { throw new Error(String.format("Did not add glyph bounded %s to node with concern %s", glyphBounds, concernBounds)); } } public void containing(Point2D p, Collection<Glyph> collector) { for (DynamicQuadTree q: quads) { if (q.concernBounds.contains(p)) {q.containing(p, collector); break;} } } public boolean isEmpty() { for (DynamicQuadTree q: quads) {if (!q.isEmpty()) {return false;}} return true; } public void items(Collection<Glyph> collector) { for (DynamicQuadTree q: quads) {q.items(collector);} } public Rectangle2D bounds() { final Rectangle2D[] bounds = new Rectangle2D[quads.length]; for (int i=0; i<bounds.length; i++) { bounds[i] = quads[i].bounds(); } return Util.fullBounds(bounds); } public String toString(int indent) { StringBuilder b = new StringBuilder(); for (DynamicQuadTree q: quads) {b.append(q.toString(indent+1));} return String.format("%sNode: %d items\n", Util.indent(indent), size()) + b.toString(); } } private static final class LeafNode extends DynamicQuadTree { private final List<Glyph> spanningItems; private final LeafQuad[] quads = new LeafQuad[4]; private int size=0; private LeafNode(Rectangle2D concernBounds) { this(concernBounds, new ArrayList<Glyph>()); } //Re-bounding version. //WARNING: This introduces data sharing and should only be done if old will immediately be destroyed private LeafNode(Rectangle2D concernBounds, LeafNode old) { this(concernBounds, old.items()); } private LeafNode(Rectangle2D concernBounds, Collection<Glyph> glyphs) { super(concernBounds); spanningItems = new ArrayList<Glyph>(LOADING); Subs subs = new Subs(concernBounds); for (int i=0; i< subs.quads.length; i++) { quads[i] = new DynamicQuadTree.LeafQuad(subs.quads[i]); } for (Glyph g: glyphs) {add(g);} } public void add(Glyph glyph) { boolean[] hits = new boolean[quads.length]; int totalHits=0; Rectangle2D glyphBounds = glyph.shape.getBounds2D(); for (int i=0; i<quads.length; i++) { LeafQuad quad = quads[i]; if (quad.concernBounds.intersects(glyphBounds)) {hits[i]=true; totalHits++;} if (totalHits>2) {break;} } if (totalHits>1) {spanningItems.add(glyph);} else {for (int i=0; i<hits.length;i++) {if (hits[i]) {quads[i].add(glyph);}}} size++; if (totalHits ==0) { throw new Error(String.format("Did not add glyph bounded %s to node with concern %s", glyphBounds, concernBounds)); } } public int size() {return size;} public String toString(int indent) { return String.format("%sLeafNode: %d items (%s spanning items)\n", Util.indent(indent), size(), spanningItems.size()); } /**Should this leaf become an inner node? Yes...but only if it would help one of the quads.**/ protected boolean doSplit() { if (size < LOADING && concernBounds.getWidth() < MIN_DIM) {return false;} for (LeafQuad q: quads) { if (q.size() > LOADING && (q.size()/(spanningItems.size()+1) > CROSS_LOAD_FACTOR)) {return true;} } return false; } //NEAR Copy public void containing(Point2D p, Collection<Glyph> collector) { for (DynamicQuadTree q: quads) { if (q.concernBounds.contains(p)) {q.containing(p, collector); break;} } for (Glyph g:spanningItems) {if (g.shape.contains(p)) {collector.add(g);}} } //NEAR Copy public boolean isEmpty() { for (DynamicQuadTree q: quads) {if (!q.isEmpty()) {return false;}} return spanningItems.size() == 0; } //Copy public Rectangle2D bounds() { final Rectangle2D[] bounds = new Rectangle2D[quads.length+1]; for (int i=0; i<quads.length; i++) { bounds[i] = quads[i].bounds(); } bounds[quads.length] = Util.bounds(spanningItems); return Util.fullBounds(bounds); } //Copy public void items(Collection<Glyph> collector) { collector.addAll(spanningItems); for (DynamicQuadTree q: quads) {q.items(collector);} } } /**Sub-leaf is a quadrant of a leaf. * It represents a set of items that would be entirely in one leaf quadrant if the leaf were to split. * This class exists so leaf-split decisions can be made efficiently. */ private static final class LeafQuad extends DynamicQuadTree { private final List<Glyph> items; protected LeafQuad(Rectangle2D concernBounds) { super (concernBounds); items = new ArrayList<Glyph>(LOADING); } //Assumes the geometry check was done by the parent public void add(Glyph glyph) { items.add(glyph); } public Rectangle2D concernBounds() {return concernBounds;} public boolean isEmpty() {return items.isEmpty();} public List<Glyph> items() {return items;} public String toString(int level) {return Util.indent(level) + "LeafQuad: " + items.size() + " items\n";} public Rectangle2D bounds() {return Util.bounds(items);} protected void items(Collection<Glyph> collector) {collector.addAll(items);} protected void containing(Point2D p, Collection<Glyph> collector) { for (Glyph g: items) {if (g.shape.contains(p)) {collector.add(g);}} } } }
package graphex; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeSet; public class DFA{ private final char EPSILON = '\u03B5'; private ArrayList<Character> alphabet; private NFAnode[] nfaList; private int nfaStart; private int nfaEnd; int nodeNum = 0; ArrayList<TreeSet<Integer>> dfaList = new ArrayList<TreeSet<Integer>>(); ArrayList<TreeSet<Integer>> epsilonClosureTable = new ArrayList<TreeSet<Integer>>(); ArrayList<DFAnode> dfaNodes = new ArrayList<DFAnode>(); TreeSet<Integer> acceptingStates = new TreeSet<Integer>(); public DFA(NFAnode[] nfa, int startState, int endState, ArrayList<Character> alpha){ alphabet = alpha; for(int i = 0; i < nfa.length; i++){ epsilonClosureTable.add(null); } nfaList = nfa; nfaEnd = endState; generateDFA(startState); System.out.println("DFA: " + dfaList); System.out.println("All States: " + dfaNodes); System.out.println("Accepting States: " + acceptingStates); } private class DFAnode{ public int number; public boolean visited = false; public HashMap<Character, Integer> edges = new HashMap<Character, Integer>(); public boolean isStart = false; public boolean isAccept = false; public DFAnode(int nodeNumber){ number = nodeNumber; } public DFAnode(int nodeNumber, boolean isAccepting){ number = nodeNumber; isAccept = isAccepting; } public void addEdge(char c, int i){ edges.put(c, i); } public String toString(){ return "DFAnode: " + number; } } private void generateDFA(int startState){ TreeSet<Integer> startNode = epsilonClosure(startState); dfaList.add(startNode); dfaNodes.add(new DFAnode(0)); System.out.println(startNode); while(nodeNum < dfaList.size()){ transitionLookup(nodeNum); nodeNum++; } } private void transitionLookup(int nodeNumber){ TreeSet<Integer> currentSet = dfaList.get(nodeNumber); DFAnode currentNode = dfaNodes.get(nodeNumber); if(currentSet.contains(nfaEnd)){ System.out.println(currentSet + " contains " + nfaEnd); acceptingStates.add(nodeNumber); } for(char trans : alphabet){ TreeSet<Integer> tempNode = new TreeSet<Integer>(); for(int i : currentSet){ ArrayList<NFAnode> edges = nfaList[i].edges.get(trans); if(edges != null){ System.out.println("Found Edges for: " + trans); for(NFAnode n : edges){ tempNode.add(n.number); for(int x : epsilonClosure(n.number)){ tempNode.add(x); } } } } if(tempNode.size() > 0 && !dfaList.contains(tempNode)) { currentNode.addEdge(trans, nodeNum); dfaList.add(tempNode); dfaNodes.add(new DFAnode(dfaList.size() - 1)); } } } private TreeSet<Integer> epsilonClosure(int number){ if(epsilonClosureTable.get(number) == null) { generateEpsilonClosure(number); } return epsilonClosureTable.get(number); } private void generateEpsilonClosure(int number){ if(epsilonClosureTable.get(number) != null) return; ArrayList<Integer> set = new ArrayList<Integer>(); TreeSet<Integer> list = new TreeSet<Integer>(); list.add(number); if(nfaList[number].edges.get(EPSILON) != null){ for(NFAnode n : nfaList[number].edges.get(EPSILON)){ set.add(n.number); list.add(n.number); } } for(int i = 0; i < set.size(); i++){ int currentNode = set.get(i); if(epsilonClosureTable.get(currentNode) == null){ if(nfaList[currentNode].edges.get(EPSILON) != null){ for(NFAnode n : nfaList[currentNode].edges.get(EPSILON)){ if(!list.contains(n.number)){ set.add(n.number); list.add(n.number); } } } } else{ for(int node: epsilonClosureTable.get(currentNode)){ if(!list.contains(node)){ set.add(node); list.add(node); } } } } epsilonClosureTable.set(number, list); //System.out.println("Added to " + number + ", The Set: " + list); } }
package com.dreiri.smarping.activities; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.Toast; import com.dreiri.smarping.R; import com.dreiri.smarping.adapters.ItemAdapter; import com.dreiri.smarping.exceptions.AlreadyExists; import com.dreiri.smarping.exceptions.NullValue; import com.dreiri.smarping.models.List; import com.dreiri.smarping.persistence.PersistenceManager; import com.dreiri.smarping.utils.EditItemDialogListener; public class ListActivity extends Activity implements EditItemDialogListener { private ListView listView; public List list = new List(); public ItemAdapter itemAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(true); PersistenceManager persistenceManager = new PersistenceManager(this); list = persistenceManager.readList(); listView = (ListView) findViewById(R.id.listView); itemAdapter = new ItemAdapter(this, list); listView.setAdapter(itemAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: scrollToTop(); break; case R.id.action_delete: Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show(); break; default: break; } return true; } public void scrollToTop() { listView.smoothScrollToPosition(0); } @Override public void onFinishEditDialog(int position, String text) { try { list.modify(position, text); } catch (NullValue e) { Toast.makeText(this, R.string.toast_null_value, Toast.LENGTH_SHORT).show(); } catch (AlreadyExists e) { Toast.makeText(this, R.string.toast_already_exists, Toast.LENGTH_SHORT).show(); } itemAdapter.refreshWithNewData(list); PersistenceManager persistenceManager = new PersistenceManager(this); persistenceManager.saveList(list); } }
package au.com.southsky.jfreesane; import java.awt.image.BufferedImage; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import au.com.southsky.jfreesane.SaneSession.SaneDeviceHandle; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; /** * Represents a SANE device within a session. SANE devices are obtained from a * {@link SaneSession}. * * <p> * Not thread-safe. * * @author James Ring (sjr@jdns.org) */ public class SaneDevice implements Closeable { private final SaneSession session; private final String name; private final String vendor; private final String model; private final String type; private SaneDeviceHandle handle; private Map<String, SaneOption> optionTitleMap = null; SaneDevice(SaneSession session, String name, String vendor, String model, String type) { this.session = session; this.name = name; this.vendor = vendor; this.model = model; this.type = type; } public String getName() { return name; } public String getVendor() { return vendor; } public String getModel() { return model; } public String getType() { return type; } private boolean isOpen() { return handle != null; } public void open() throws IOException { Preconditions.checkState(!isOpen(), "device is already open"); handle = session.openDevice(this); } public BufferedImage acquireImage() throws IOException { Preconditions.checkState(isOpen(), "device is not open"); return session.acquireImage(handle); } @Override public void close() throws IOException { if (!isOpen()) { throw new IOException("device is already closed"); } session.closeDevice(handle); handle = null; } @Override public String toString() { return "SaneDevice [name=" + name + ", vendor=" + vendor + ", model=" + model + ", type=" + type + "]"; } public SaneDeviceHandle getHandle() { return handle; } /** * Implements SANE_NET_GET_OPTION_DESCRIPTORS * * @return List of SaneOptions * @throws IOException */ public List<SaneOption> listOptions() throws IOException { if (optionTitleMap == null) { optionTitleMap = Maps.uniqueIndex(SaneOption.optionsFor(this), new Function<SaneOption, String>() { @Override public String apply(SaneOption input) { return input.getName(); } }); } // Maps.uniqueIndex guarantees the order of optionTitleMap.values() return ImmutableList.copyOf(optionTitleMap.values()); } public SaneOption getOption(String title) throws IOException { listOptions(); return optionTitleMap.get(title); } public SaneSession getSession() { return session; } }
package com.amee.platform.science; import org.apache.commons.lang.StringUtils; import javax.measure.quantity.Power; import javax.measure.quantity.Quantity; import javax.measure.unit.*; import java.text.ParseException; import java.text.ParsePosition; /** * An AmountUnit represents the unit of an Amount, eg kWh. * */ public class AmountUnit { protected final static UnitFormat UNIT_FORMAT = UnitFormat.getInstance(); // Define various watt based units. private final static Unit<Power> KILOWATT = SI.WATT.times(1000); private final static Unit<Power> MEGAWATT = KILOWATT.times(1000); private final static Unit<Power> GIGAWATT = MEGAWATT.times(1000); private final static Unit<Power> TERAWATT = GIGAWATT.times(1000); private final static Unit<? extends Quantity> KILOWATT_HOUR = KILOWATT.times(NonSI.HOUR); private final static Unit<? extends Quantity> MEGAWATT_HOUR = MEGAWATT.times(NonSI.HOUR); private final static Unit<? extends Quantity> GIGAWATT_HOUR = GIGAWATT.times(NonSI.HOUR); private final static Unit<? extends Quantity> TERAWATT_HOUR = TERAWATT.times(NonSI.HOUR); // Define BTUs. private final static Unit<? extends Quantity> BTU_39F = SI.JOULE.times(1059.67); private final static Unit<? extends Quantity> BTU_MEAN = SI.JOULE.times(1055.87); private final static Unit<? extends Quantity> BTU_IT = SI.JOULE.times(1055.05585262); private final static Unit<? extends Quantity> BTU_ISO = SI.JOULE.times(1055.056); private final static Unit<? extends Quantity> BTU_59F = SI.JOULE.times(1054.804); private final static Unit<? extends Quantity> BTU_60F = SI.JOULE.times(1054.68); private final static Unit<? extends Quantity> BTU_63F = SI.JOULE.times(1054.6); private final static Unit<? extends Quantity> BTU_THERMOCHEMICAL = SI.JOULE.times(1054.35026444); // Define THERMs. private final static Unit<? extends Quantity> THERM_39F = BTU_39F.times(100000); private final static Unit<? extends Quantity> THERM_MEAN = BTU_MEAN.times(100000); private final static Unit<? extends Quantity> THERM_IT = BTU_IT.times(100000); private final static Unit<? extends Quantity> THERM_ISO = BTU_ISO.times(100000); private final static Unit<? extends Quantity> THERM_59F = BTU_59F.times(100000); private final static Unit<? extends Quantity> THERM_60F = BTU_60F.times(100000); private final static Unit<? extends Quantity> THERM_63F = BTU_63F.times(100000); private final static Unit<? extends Quantity> THERM_THERMOCHEMICAL = BTU_THERMOCHEMICAL.times(100000); // Define barrels private final static Unit<? extends Quantity> BARREL_OIL = NonSI.GALLON_LIQUID_US.times(42); // Define Ecoinvent. private final static Unit<? extends Quantity> DALYS = Unit.ONE; private final static Unit<? extends Quantity> ELU = Unit.ONE; private final static Unit<? extends Quantity> LU = Unit.ONE; private final static Unit<? extends Quantity> NM3 = Unit.ONE; private final static Unit<? extends Quantity> UBP = Unit.ONE; private final static Unit<? extends Quantity> M2 = Unit.ONE; private final static Unit<? extends Quantity> M2A = Unit.ONE; private final static Unit<? extends Quantity> M3 = Unit.ONE; private final static Unit<? extends Quantity> M3A = Unit.ONE; private final static Unit<? extends Quantity> MA = Unit.ONE; private final static Unit<? extends Quantity> MOLES = Unit.ONE; private final static Unit<? extends Quantity> PERSON = Unit.ONE; private final static Unit<? extends Quantity> PIG = Unit.ONE; private final static Unit<? extends Quantity> PKM = Unit.ONE; private final static Unit<? extends Quantity> POINTS = Unit.ONE; private final static Unit<? extends Quantity> TKM = Unit.ONE; private final static Unit<? extends Quantity> UNIT = Unit.ONE; private final static Unit<? extends Quantity> VKM = Unit.ONE; { // Create usable ASCII representations. JScience will use non-ASCII characters by default. UNIT_FORMAT.label(KILOWATT_HOUR, "kWh"); UNIT_FORMAT.label(MEGAWATT_HOUR, "MWh"); UNIT_FORMAT.label(GIGAWATT_HOUR, "GWh"); UNIT_FORMAT.label(TERAWATT_HOUR, "TWh"); // BTUs. UNIT_FORMAT.label(BTU_39F, "BTU_ThirtyNineF"); UNIT_FORMAT.label(SI.KILO(BTU_39F), "kBTU_ThirtyNineF"); UNIT_FORMAT.label(SI.MEGA(BTU_39F), "MBTU_ThirtyNineF"); UNIT_FORMAT.alias(SI.MEGA(BTU_39F), "MMBTU_ThirtyNineF"); UNIT_FORMAT.alias(SI.MEGA(BTU_39F), "mmBTU_ThirtyNineF"); UNIT_FORMAT.label(SI.GIGA(BTU_39F), "GBTU_ThirtyNineF"); UNIT_FORMAT.label(SI.TERA(BTU_39F), "TBTU_ThirtyNineF"); UNIT_FORMAT.label(BTU_MEAN, "BTU_Mean"); UNIT_FORMAT.label(SI.KILO(BTU_MEAN), "kBTU_Mean"); UNIT_FORMAT.label(SI.MEGA(BTU_MEAN), "MBTU_Mean"); UNIT_FORMAT.alias(SI.MEGA(BTU_MEAN), "MMBTU_Mean"); UNIT_FORMAT.alias(SI.MEGA(BTU_MEAN), "mmBTU_Mean"); UNIT_FORMAT.label(SI.GIGA(BTU_MEAN), "GBTU_Mean"); UNIT_FORMAT.label(SI.TERA(BTU_MEAN), "TBTU_Mean"); UNIT_FORMAT.label(BTU_IT, "BTU_IT"); UNIT_FORMAT.label(SI.KILO(BTU_IT), "kBTU_IT"); UNIT_FORMAT.label(SI.MEGA(BTU_IT), "MBTU_IT"); UNIT_FORMAT.alias(SI.MEGA(BTU_IT), "MMBTU_IT"); UNIT_FORMAT.alias(SI.MEGA(BTU_IT), "mmBTU_IT"); UNIT_FORMAT.label(SI.GIGA(BTU_IT), "GBTU_IT"); UNIT_FORMAT.label(SI.TERA(BTU_IT), "TBTU_IT"); UNIT_FORMAT.label(BTU_ISO, "BTU_ISO"); UNIT_FORMAT.label(SI.KILO(BTU_ISO), "kBTU_ISO"); UNIT_FORMAT.label(SI.MEGA(BTU_ISO), "MBTU_ISO"); UNIT_FORMAT.label(SI.MEGA(BTU_ISO), "MMBTU_ISO"); UNIT_FORMAT.label(SI.MEGA(BTU_ISO), "mmBTU_ISO"); UNIT_FORMAT.label(SI.GIGA(BTU_ISO), "GBTU_ISO"); UNIT_FORMAT.label(SI.TERA(BTU_ISO), "TBTU_ISO"); UNIT_FORMAT.label(BTU_59F, "BTU_FiftyNineF"); UNIT_FORMAT.label(SI.KILO(BTU_59F), "kBTU_FiftyNineF"); UNIT_FORMAT.label(SI.MEGA(BTU_59F), "MBTU_FiftyNineF"); UNIT_FORMAT.alias(SI.MEGA(BTU_59F), "MMBTU_FiftyNineF"); UNIT_FORMAT.alias(SI.MEGA(BTU_59F), "mmBTU_FiftyNineF"); UNIT_FORMAT.label(SI.GIGA(BTU_59F), "GBTU_FiftyNineF"); UNIT_FORMAT.label(SI.TERA(BTU_59F), "TBTU_FiftyNineF"); UNIT_FORMAT.label(BTU_60F, "BTU_SixtyF"); UNIT_FORMAT.label(SI.KILO(BTU_60F), "kBTU_SixtyF"); UNIT_FORMAT.label(SI.MEGA(BTU_60F), "MBTU_SixtyF"); UNIT_FORMAT.alias(SI.MEGA(BTU_60F), "MMBTU_SixtyF"); UNIT_FORMAT.alias(SI.MEGA(BTU_60F), "mmBTU_SixtyF"); UNIT_FORMAT.label(SI.GIGA(BTU_60F), "GBTU_SixtyF"); UNIT_FORMAT.label(SI.TERA(BTU_60F), "TBTU_SixtyF"); UNIT_FORMAT.label(BTU_63F, "BTU_SixtyThreeF"); UNIT_FORMAT.label(SI.KILO(BTU_63F), "kBTU_SixtyThreeF"); UNIT_FORMAT.label(SI.MEGA(BTU_63F), "MBTU_SixtyThreeF"); UNIT_FORMAT.alias(SI.MEGA(BTU_63F), "MMBTU_SixtyThreeF"); UNIT_FORMAT.alias(SI.MEGA(BTU_63F), "mmBTU_SixtyThreeF"); UNIT_FORMAT.label(SI.GIGA(BTU_63F), "GBTU_SixtyThreeF"); UNIT_FORMAT.label(SI.TERA(BTU_63F), "TBTU_SixtyThreeF"); UNIT_FORMAT.label(BTU_THERMOCHEMICAL, "BTU_Thermochemical"); UNIT_FORMAT.label(SI.KILO(BTU_THERMOCHEMICAL), "kBTU_Thermochemical"); UNIT_FORMAT.label(SI.MEGA(BTU_THERMOCHEMICAL), "MBTU_Thermochemical"); UNIT_FORMAT.alias(SI.MEGA(BTU_THERMOCHEMICAL), "MMBTU_Thermochemical"); UNIT_FORMAT.alias(SI.MEGA(BTU_THERMOCHEMICAL), "mmBTU_Thermochemical"); UNIT_FORMAT.label(SI.GIGA(BTU_THERMOCHEMICAL), "GBTU_Thermochemical"); UNIT_FORMAT.label(SI.TERA(BTU_THERMOCHEMICAL), "TBTU_Thermochemical"); // THERMs. UNIT_FORMAT.label(THERM_39F, "thm_ThirtyNineF"); UNIT_FORMAT.label(THERM_MEAN, "thm_Mean"); UNIT_FORMAT.label(THERM_IT, "thm_IT"); UNIT_FORMAT.alias(THERM_IT, "thm_ec"); UNIT_FORMAT.label(THERM_ISO, "thm_ISO"); UNIT_FORMAT.label(THERM_59F, "thm_FiftyNineF"); UNIT_FORMAT.alias(THERM_59F, "thm_us"); UNIT_FORMAT.label(THERM_60F, "thm_SixtyF"); UNIT_FORMAT.label(THERM_63F, "thm_SixtyThreeF"); UNIT_FORMAT.label(THERM_THERMOCHEMICAL, "thm_Thermochemical"); // Ensure that "gal" and "oz" are sensible for AMEE. // JScience will bizarrely default "gal" and "oz" to UK units for UK Locale. UNIT_FORMAT.label(NonSI.GALLON_LIQUID_US, "gal"); UNIT_FORMAT.label(NonSI.OUNCE, "oz"); // For GALLON_UK, explicitly declare gal_uk as canonical and gallon_uk as the alias. UNIT_FORMAT.label(NonSI.GALLON_UK, "gal_uk"); UNIT_FORMAT.alias(NonSI.GALLON_UK, "gallon_uk"); // Need to explicitly declare these otherwise we get a parse error. UNIT_FORMAT.label(NonSI.OUNCE_LIQUID_US, "oz_fl"); UNIT_FORMAT.label(NonSI.OUNCE_LIQUID_UK, "oz_fl_uk"); // Barrel UNIT_FORMAT.label(BARREL_OIL, "bbl"); // Ecoinvent. UNIT_FORMAT.label(DALYS, "DALYs"); UNIT_FORMAT.label(ELU, "ELU"); UNIT_FORMAT.label(LU, "LU"); UNIT_FORMAT.label(NM3, "Nm_three"); // Was Nm3. UNIT_FORMAT.label(UBP, "UBP"); UNIT_FORMAT.label(M2, "m_two"); // Was m2. UNIT_FORMAT.label(M2A, "m_two_a"); // was m2a. UNIT_FORMAT.label(M3, "m_three"); // Was m3. UNIT_FORMAT.label(M3A, "m_three_a"); // was m3a. UNIT_FORMAT.label(MA, "ma"); UNIT_FORMAT.label(MOLES, "moles"); UNIT_FORMAT.label(PERSON, "person"); UNIT_FORMAT.label(PIG, "pig"); UNIT_FORMAT.label(PKM, "pkm"); UNIT_FORMAT.label(POINTS, "points"); UNIT_FORMAT.label(TKM, "tkm"); UNIT_FORMAT.label(UNIT, "unit"); UNIT_FORMAT.label(VKM, "vkm"); } public static final AmountUnit ONE = new AmountUnit(Unit.ONE); protected Unit unit = Unit.ONE; public AmountUnit(Unit unit) { this.unit = unit; } public static AmountUnit valueOf(String unit) { return new AmountUnit(internalValueOf(unit)); } public AmountCompoundUnit with(AmountPerUnit perUnit) { return AmountCompoundUnit.valueOf(this, perUnit); } public boolean isCompatibleWith(String unit) { return StringUtils.isNotBlank(unit) && this.unit.isCompatible(internalValueOf(unit)); } // This is like Unit.valueOf but forces use of UNIT_FORMAT instead. protected static Unit<? extends Quantity> internalValueOf(CharSequence unit) { if ((unit == null) || (unit.length() == 0)) { throw new IllegalArgumentException("The unit argument is blank."); } try { return UNIT_FORMAT.parseProductUnit(unit, new ParsePosition(0)); } catch (ParseException e) { throw new IllegalArgumentException(e); } } /** * Compares this AmountUnit with the specified Object for equality. * This method considers two AmountUnit objects equal only if they are equal type and unit. * Note that mixed-type comparison is allowed, but a subclass will never compare equal to this. * * @param o Object to which this AmountUnit is to be compared. * @return true if and only if the specified Object is an AmountUnit whose unit is equal to this AmountUnit's. */ @Override public boolean equals(Object o) { if (o == this) { return true; } if (o != null && getClass() == o.getClass()) { AmountUnit a = (AmountUnit) o; return unit.equals(a.unit); } return false; } /** * Returns the hash code for this AmountUnit. * * @return hash code for this AmountUnit. */ @Override public int hashCode() { return unit.hashCode(); } public Unit toUnit() { return unit; } @Override public String toString() { return UNIT_FORMAT.format(toUnit()); } }
package com.bio4j.model.go.programs; import com.bio4j.model.go.GoGraph; import com.bio4j.model.go.nodes.GoTerm; import com.bio4j.model.go.nodes.SubOntologies; import com.ohnosequences.xml.api.model.XMLElement; import org.jdom2.Element; import java.io.*; import java.util.*; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * @author <a href="mailto:ppareja@era7.com">Pablo Pareja Tobes</a> */ public abstract class ImportGO { public static final String TERM_TAG_NAME = "term"; public static final String ID_TAG_NAME = "id"; public static final String NAME_TAG_NAME = "name"; public static final String DEF_TAG_NAME = "def"; public static final String DEFSTR_TAG_NAME = "defstr"; public static final String IS_ROOT_TAG_NAME = "is_root"; public static final String IS_OBSOLETE_TAG_NAME = "is_obsolete"; public static final String COMMENT_TAG_NAME = "comment"; public static final String NAMESPACE_TAG_NAME = "namespace"; public static final String RELATIONSHIP_TAG_NAME = "relationship"; public static final String REGULATES_OBOXML_RELATIONSHIP_NAME = "regulates"; public static final String POSITIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME = "positively_regulates"; public static final String NEGATIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME = "negatively_regulates"; public static final String PART_OF_OBOXML_RELATIONSHIP_NAME = "part_of"; public static final String HAS_PART_OF_OBOXML_RELATIONSHIP_NAME = "has_part"; public static final String IS_A_OBOXML_RELATIONSHIP_NAME = "is_a"; private static final Logger logger = Logger.getLogger("ImportGO"); private static FileHandler fh; protected abstract GoGraph config(); protected void importGO(String[] args){ if (args.length != 2) { System.out.println("This program expects the following parameters: \n" + "1. Gene ontology xml filename \n" + "2. Bio4j DB folder \n"); } else { int termCounter = 0; int limitForPrintingOut = 10000; long initTime = System.nanoTime(); File inFile = new File(args[0]); BufferedWriter statsBuff = null; GoGraph goGraph = config(); try { //This block configures the logger with handler and formatter fh = new FileHandler("ImportGO.log", true); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.addHandler(fh); logger.setLevel(Level.ALL); statsBuff = new BufferedWriter(new FileWriter(new File("ImportGOStats.txt"))); Map<String, ArrayList<String>> termParentsMap = new HashMap<>(); Map<String, ArrayList<String>> regulatesMap = new HashMap<>(); Map<String, ArrayList<String>> negativelyRegulatesMap = new HashMap<>(); Map<String, ArrayList<String>> positivelyRegulatesMap = new HashMap<>(); Map<String, ArrayList<String>> partOfMap = new HashMap<>(); Map<String, ArrayList<String>> hasPartMap = new HashMap<>(); BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line; StringBuilder termStBuilder = new StringBuilder(); logger.log(Level.INFO, "inserting subontologies nodes...."); SubOntologies subOntologiesBP = graph.subOntologiesT.from(graph.rawGraph().addVertex(null)); subOntologiesBP.set(graph.subOntologiesT.name, "biological_process"); SubOntologies subOntologiesCC = graph.subOntologiesT.from(graph.rawGraph().addVertex(null)); subOntologiesCC.set(graph.subOntologiesT.name, "cellular_component"); SubOntologies subOntologiesMM = graph.subOntologiesT.from(graph.rawGraph().addVertex(null)); subOntologiesMM.set(graph.subOntologiesT.name, "molecular_function"); logger.log(Level.INFO, "inserting term nodes...."); while ((line = reader.readLine()) != null) { if (line.trim().startsWith("<" + TERM_TAG_NAME)) { while (!line.trim().startsWith("</" + TERM_TAG_NAME + ">")) { termStBuilder.append(line); line = reader.readLine(); } //organism final line termStBuilder.append(line); XMLElement termXMLElement = new XMLElement(termStBuilder.toString()); termStBuilder.delete(0, termStBuilder.length()); String goId = termXMLElement.asJDomElement().getChildText(ID_TAG_NAME); String goName = termXMLElement.asJDomElement().getChildText(NAME_TAG_NAME); if (goName == null) { goName = ""; } String goNamespace = termXMLElement.asJDomElement().getChildText(NAMESPACE_TAG_NAME); if (goNamespace == null) { goNamespace = ""; } String goDefinition = ""; Element defElem = termXMLElement.asJDomElement().getChild(DEF_TAG_NAME); if (defElem != null) { Element defstrElem = defElem.getChild(DEFSTR_TAG_NAME); if (defstrElem != null) { goDefinition = defstrElem.getText(); } } String goComment = termXMLElement.asJDomElement().getChildText(COMMENT_TAG_NAME); if (goComment == null) { goComment = ""; } String goIsObsolete = termXMLElement.asJDomElement().getChildText(IS_OBSOLETE_TAG_NAME); if (goIsObsolete == null) { goIsObsolete = ""; } else { if (goIsObsolete.equals("1")) { goIsObsolete = "true"; } else { goIsObsolete = "false"; } } List<Element> termParentTerms = termXMLElement.asJDomElement().getChildren(IS_A_OBOXML_RELATIONSHIP_NAME); ArrayList<String> array = new ArrayList<>(); for (Element elem : termParentTerms) { array.add(elem.getText().trim()); } termParentsMap.put(goId, array); List<Element> relationshipTags = termXMLElement.asJDomElement().getChildren(RELATIONSHIP_TAG_NAME); for (Element relationshipTag : relationshipTags) { String relType = relationshipTag.getChildText("type"); String toSt = relationshipTag.getChildText("to"); if (relType.equals(REGULATES_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = regulatesMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); regulatesMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(POSITIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = positivelyRegulatesMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); positivelyRegulatesMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(NEGATIVELY_REGULATES_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = negativelyRegulatesMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); negativelyRegulatesMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(PART_OF_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = partOfMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); partOfMap.put(goId, tempArray); } tempArray.add(toSt); } else if (relType.equals(HAS_PART_OF_OBOXML_RELATIONSHIP_NAME)) { ArrayList<String> tempArray = hasPartMap.get(goId); if (tempArray == null) { tempArray = new ArrayList<>(); hasPartMap.put(goId, tempArray); } tempArray.add(toSt); } } GoTerm term = goGraph.GoTerm().from(goGraph.raw().addVertex(goGraph.GoTerm())); term.set(goGraph.GoTerm().id, goId); term.set(goGraph.GoTerm().name, goName); term.set(goGraph.GoTerm().definition, goDefinition); //term.set(goGraph.GoTerm().obso, goIsObsolete); term.set(goGraph.GoTerm().comment, goComment); //g.commit(); TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(goId).get(); TitanSubOntologies titanSubontologies = graph.subOntologiesNameIndex.getNode(goNamespace).get(); tempGoTerm.addOut(graph.subOntologyT, titanSubontologies); } termCounter++; if ((termCounter % limitForPrintingOut) == 0) { logger.log(Level.INFO, (termCounter + " terms inserted!!")); } } reader.close(); goGraph.raw().commit(); logger.log(Level.INFO, "Inserting relationships...."); logger.log(Level.INFO, "'is_a' relationships...."); Set<String> keys = termParentsMap.keySet(); for (String key : keys) { TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(key).get(); //System.out.println("id: " + tempGoTerm.id() + " name: " + tempGoTerm.name()); ArrayList<String> tempArray = termParentsMap.get(key); for (String string : tempArray) { //System.out.println("string: " + string); TitanGoTerm tempGoTerm2 = graph.goTermIdIndex.getNode(string).get(); //System.out.println("id2: " + tempGoTerm2.id() + " name2: " + tempGoTerm2.name()); tempGoTerm.addOut(graph.isAT, tempGoTerm2); } } logger.log(Level.INFO, "'regulates' relationships...."); keys = regulatesMap.keySet(); for (String key : keys) { TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(key).get(); ArrayList<String> tempArray = regulatesMap.get(key); for (String string : tempArray) { TitanGoTerm tempGoTerm2 = graph.goTermIdIndex.getNode(string).get(); tempGoTerm.addOut(graph.regulatesT, tempGoTerm2); } } logger.log(Level.INFO, "'negatively_regulates' relationships...."); keys = negativelyRegulatesMap.keySet(); for (String key : keys) { TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(key).get(); ArrayList<String> tempArray = negativelyRegulatesMap.get(key); for (String string : tempArray) { TitanGoTerm tempGoTerm2 = graph.goTermIdIndex.getNode(string).get(); tempGoTerm.addOut(graph.negativelyRegulatesT, tempGoTerm2); } } logger.log(Level.INFO, "'positively_regulates' relationships...."); keys = positivelyRegulatesMap.keySet(); for (String key : keys) { TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(key).get(); ArrayList<String> tempArray = positivelyRegulatesMap.get(key); for (String string : tempArray) { TitanGoTerm tempGoTerm2 = graph.goTermIdIndex.getNode(string).get(); tempGoTerm.addOut(graph.positivelyRegulatesT, tempGoTerm2); } } logger.log(Level.INFO, "'part_of' relationships...."); keys = partOfMap.keySet(); for (String key : keys) { TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(key).get(); ArrayList<String> tempArray = partOfMap.get(key); for (String string : tempArray) { TitanGoTerm tempGoTerm2 = graph.goTermIdIndex.getNode(string).get(); tempGoTerm.addOut(graph.partOfT, tempGoTerm2); } } logger.log(Level.INFO, "'has_part_of' relationships...."); keys = hasPartMap.keySet(); for (String key : keys) { TitanGoTerm tempGoTerm = graph.goTermIdIndex.getNode(key).get(); ArrayList<String> tempArray = hasPartMap.get(key); for (String string : tempArray) { TitanGoTerm tempGoTerm2 = graph.goTermIdIndex.getNode(string).get(); tempGoTerm.addOut(graph.hasPartOfT, tempGoTerm2); } } logger.log(Level.INFO, "Done! :)"); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement stackTraceElement : trace) { logger.log(Level.SEVERE, stackTraceElement.toString()); } } finally { try { //closing logger file handler fh.close(); logger.log(Level.INFO, "Closing up manager...."); //shutdown, makes sure all changes are written to disk graph.rawGraph().shutdown(); long elapsedTime = System.nanoTime() - initTime; long elapsedSeconds = Math.round((elapsedTime / 1000000000.0)); long hours = elapsedSeconds / 3600; long minutes = (elapsedSeconds % 3600) / 60; long seconds = (elapsedSeconds % 3600) % 60; statsBuff.write("Statistics for program ImportGeneOntology:\nInput file: " + inFile.getName() + "\nThere were " + termCounter + " terms inserted.\n" + "The elapsed time was: " + hours + "h " + minutes + "m " + seconds + "s\n"); statsBuff.close(); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); StackTraceElement[] trace = e.getStackTrace(); for (StackTraceElement stackTraceElement : trace) { logger.log(Level.SEVERE, stackTraceElement.toString()); } } } } } }
package edu.wustl.catissuecore.util.global; /** * This class stores the constants used in the operations in the application. * @author gautam_shetty */ public class Constants extends edu.wustl.common.util.global.Constants { //Constants added for Catissuecore V1.2 public static final String PAGE_OF_ADMINISTRATOR = "pageOfAdministrator"; public static final String PAGE_OF_SUPERVISOR = "pageOfSupervisor"; public static final String PAGE_OF_TECHNICIAN = "pageOfTechnician"; public static final String PAGE_OF_SCIENTIST = "pageOfScientist"; //Constants added for Validation public static final String DEFAULT_TISSUE_SITE ="defaultTissueSite"; public static final String DEFAULT_CLINICAL_STATUS ="defaultClinicalStatus"; public static final String DEFAULT_GENDER = "defaultGender"; public static final String DEFAULT_GENOTYPE = "defaultGenotype"; public static final String DEFAULT_SPECIMEN = "defaultSpecimen"; public static final String DEFAULT_TISSUE_SIDE = "defaultTissueSide"; public static final String DEFAULT_PATHOLOGICAL_STATUS = "defaultPathologicalStatus"; public static final String DEFAULT_RECEIVED_QUALITY= "defaultReceivedQuality"; public static final String DEFAULT_FIXATION_TYPE = "defaultFixationType"; public static final String DEFAULT_COLLECTION_PROCEDURE="defaultCollectionProcedure"; public static final String DEFAULT_CONTAINER= "defaultContainer"; public static final String DEFAULT_METHOD= "defaultMethod"; public static final String DEFAULT_EMBEDDING_MEDIUM="defaultEmbeddingMedium"; public static final String DEFAULT_BIOHAZARD="defaultBiohazard"; public static final String DEFAULT_SITE_TYPE ="defaultSiteType"; public static final String DEFAULT_SPECIMEN_TYPE ="defaultSpecimenType"; public static final String DEFAULT_ETHNICITY ="defaultEthnicity"; public static final String DEFAULT_RACE ="defaultRace"; public static final String DEFAULT_CLINICAL_DIAGNOSIS = "defaultClinicalDiagnosis"; public static final String DEFAULT_STATES ="defaultStates"; public static final String DEFAULT_COUNTRY ="defaultCountry"; public static final String DEFAULT_HISTOLOGICAL_QUALITY="defaultHistologicalQuality"; public static final String DEFAULT_VITAL_STATUS ="defaultVitalStatus"; //Consent tracking public static final String SHOW_CONSENTS="showConsents"; public static final String SPECIMEN_CONSENTS="specimenConsents"; public static final String YES="yes"; public static final String CP_ID="cpID"; public static final String BARCODE_LABLE="barcodelabel"; public static final String DISTRIBUTION_ON="labelBarcode"; public static final String POPUP="popup"; public static final String ERROR="error"; public static final String ERROR_SHOWCONSENTS="errorShowConsent"; public static final String COMPLETE="Complete"; public static final String VIEW_CONSENTS="View"; public static final String APPLY="Apply"; public static final String APPLY_ALL="ApplyAll"; public static final String APPLY_NONE="ApplyNone"; public static final String PREDEFINED_CADSR_CONSENTS="predefinedConsentsList"; public static final String DISABLED="disabled"; public static final String VIEWAll="ViewAll"; public static final String BARCODE_DISTRIBUTION="1"; public static final String LABLE_DISTRIBUTION="2"; public static final String CONSENT_WAIVED="Consent Waived"; public static final String NO_CONSENTS="No Consents"; public static final String NO_CONSENTS_DEFINED="None Defined"; public static final String INVALID="Invalid"; public static final String VALID="valid"; public static final String FALSE="false"; public static final String TRUE="true"; public static final String NULL="null"; public static final String CONSENT_TABLE="tableId4"; public static final String DISABLE="disable"; public static final String SCG_ID="-1"; public static final String SELECTED_TAB="tab"; public static final String TAB_SELECTED="tabSelected"; public static final String NEWSPECIMEN_FORM="newSpecimenForm"; public static final String CONSENT_TABLE_SHOWHIDE="tableStatus"; public static final String SPECIMEN_RESPONSELIST="specimenResponseList"; public static final String PROTOCOL_EVENT_ID="protocolEventId"; public static final String SCG_DROPDOWN="value"; public static final String HASHED_OUT=" public static final String VERIFIED="Verified"; public static final String STATUS="status"; public static final String NOT_APPLICABLE="Not Applicable"; public static final String WITHDRAW_ALL="withrawall"; public static final String RESPONSE="response"; public static final String WITHDRAW="withdraw"; public static final String VIRTUALLY_LOCATED="Virtually Located"; public static final String LABLE="Lable"; public static final String STORAGE_CONTAINER_LOCATION="Storage Container Location"; public static final String CLASS_NAME="Class Name"; public static final String SPECIMEN_LIST="specimenDetails"; public static final String COLUMNLIST="columnList"; public static final String CONSENT_RESPONSE_KEY="CR_"; public static final String CONSENT_RESPONSE="ConsentResponse"; public static final String SPECIMEN_LIST_SESSION_MAP = "SpecimenListBean"; public static final String COLLECTION_PROTOCOL_EVENT_SESSION_MAP = "collectionProtocolEventMap"; public static final String COLLECTION_PROTOCOL_SESSION_BEAN = "collectionProtocolBean"; public static final String [][] defaultValueKeys= { {Constants.DEFAULT_TISSUE_SITE, edu.wustl.common.util.global.Constants.CDE_NAME_TISSUE_SITE}, {Constants.DEFAULT_CLINICAL_STATUS, Constants.CDE_NAME_CLINICAL_STATUS}, {Constants.DEFAULT_GENDER, Constants.CDE_NAME_GENDER}, {Constants.DEFAULT_GENOTYPE, Constants.CDE_NAME_GENOTYPE}, {Constants.DEFAULT_SPECIMEN, Constants.CDE_NAME_SPECIMEN_CLASS}, {Constants.DEFAULT_TISSUE_SIDE, Constants.CDE_NAME_TISSUE_SIDE}, {Constants.DEFAULT_PATHOLOGICAL_STATUS, Constants.CDE_NAME_PATHOLOGICAL_STATUS}, {Constants.DEFAULT_RECEIVED_QUALITY, Constants.CDE_NAME_RECEIVED_QUALITY}, {Constants.DEFAULT_FIXATION_TYPE, Constants.CDE_NAME_FIXATION_TYPE}, {Constants.DEFAULT_COLLECTION_PROCEDURE, Constants.CDE_NAME_COLLECTION_PROCEDURE}, {Constants.DEFAULT_CONTAINER, Constants.CDE_NAME_CONTAINER}, {Constants.DEFAULT_METHOD, Constants.CDE_NAME_METHOD}, {Constants.DEFAULT_EMBEDDING_MEDIUM,Constants.CDE_NAME_EMBEDDING_MEDIUM}, {Constants.DEFAULT_BIOHAZARD, Constants.CDE_NAME_BIOHAZARD}, {Constants.DEFAULT_SITE_TYPE, Constants.CDE_NAME_SITE_TYPE}, {Constants.DEFAULT_SPECIMEN_TYPE, Constants.CDE_NAME_SPECIMEN_TYPE}, {Constants.DEFAULT_ETHNICITY, Constants.CDE_NAME_ETHNICITY}, {Constants.DEFAULT_RACE, Constants.CDE_NAME_RACE}, {Constants.DEFAULT_CLINICAL_DIAGNOSIS, Constants.CDE_NAME_CLINICAL_DIAGNOSIS}, {Constants.DEFAULT_STATES, Constants.CDE_NAME_STATE_LIST}, {Constants.DEFAULT_COUNTRY, Constants.CDE_NAME_COUNTRY_LIST}, {Constants.DEFAULT_HISTOLOGICAL_QUALITY, Constants.CDE_NAME_HISTOLOGICAL_QUALITY}, {Constants.DEFAULT_VITAL_STATUS, Constants.CDE_VITAL_STATUS} }; //Constants added for Catissuecore V1.2 public static final String MYSQL_NUM_TO_STR_FUNCTION_NAME_FOR_LABEL_GENRATION= "cast(label as signed)"; public static final String ORACLE_NUM_TO_STR_FUNCTION_NAME_FOR_LABEL_GENRATION = "catissue_label_to_num(label)"; // Query Module Interface UI constants public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do"; public static final String categorySearchForm = "categorySearchForm"; public static final String SearchCategory = "SearchCategory.do"; public static final String DefineSearchResultsViewAction = "DefineSearchResultsView.do"; public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do"; public static final String QUERY_DAG_VIEW_APPLET = "edu/wustl/catissuecore/applet/ui/querysuite/DiagrammaticViewApplet.class"; public static final String QUERY_DAG_VIEW_APPLET_NAME = "Dag View Applet"; public static final String APP_DYNAMIC_UI_XML = "xmlfile.dynamicUI"; public static final String QUERY_CONDITION_DELIMITER = "@#condition#@"; public static final String QUERY_OPERATOR_DELIMITER = "!*=*!"; public static final String SEARCHED_ENTITIES_MAP = "searchedEntitiesMap"; public static final String SUCCESS = "success"; public static final String LIST_OF_ENTITIES_IN_QUERY = "ListOfEntitiesInQuery"; public static final String DYNAMIC_UI_XML = "dynamicUI.xml"; public static final String TREE_DATA = "treeData"; public static final String ZERO_ID = "0"; public static final String TEMP_OUPUT_TREE_TABLE_NAME = "temp_OutputTree"; public static final String CREATE_TABLE = "Create table "; public static final String AS = "as"; public static final String UNDERSCORE = "_"; public static final String ID_NODES_MAP = "idNodesMap"; public static final String ID_COLUMNS_MAP = "idColumnsMap"; public static final String COLUMN_NAME = "Column"; public static final String[] ATTRIBUTE_NAMES_FOR_TREENODE_LABEL = { "firstName", "lastName", "title", "name", "label" }; public static final String MISSING_TWO_VALUES = "missingTwoValues"; public static final String DATE = "date"; public static final String DEFINE_RESULTS_VIEW = "DefineResultsView"; public static final String CURRENT_PAGE = "currentPage"; public static final String ADD_LIMITS = "AddLimits"; public static final String LABEL_TREE_NODE = "Label"; public static final String ENTITY_NAME = "Entity Name"; public static final String COUNT = "Count"; public static final String TREE_NODE_FONT = "<font color='#FF9BFF' face='Verdana'><i>"; public static final String TREE_NODE_FONT_CLOSE = "</i></font>"; public static final String NULL_ID = "NULL"; public static final String NODE_SEPARATOR = "::"; public static final String DEFINE_SEARCH_RULES = "Define Limits For"; public static final String DATE_FORMAT = "MM-dd-yyyy"; public static final String OUTPUT_TREE_MAP = "outputTreeMap"; public static final String CHECK_ALL_PAGES = "checkAllPages"; public static final String CHECK_ALL_ACROSS_ALL_PAGES = "isCheckAllAcrossAllChecked"; public static final String CLASSES_PRESENT_IN_QUERY = "Objects Present In Query"; public static final String DEFINE_QUERY_RESULTS_VIEW_ACTION = "DefineQueryResultsView.do"; public static final String CONFIGURE_GRID_VIEW_ACTION = "ConfigureGridView.do"; public static String ATTRIBUTE_MAP = "attributeMap"; public static final String CLASS = "class"; public static final String ATTRIBUTE = "attribute"; public static final String SELECT_DISTINCT = "select distinct "; public static final String FROM = " from "; public static final String WHERE = " where "; public static final String SELECTED_COLUMN_META_DATA = "selectedColumnMetaData"; public static final String CURRENT_SELECTED_OBJECT = "currentSelectedObject"; public static final String SELECTED_COLUMN_NAME_VALUE_BEAN_LIST = "selectedColumnNameValueBeanList"; // Frame names in Query Module Results page. public static final String GRID_DATA_VIEW_FRAME = "gridFrame"; public static final String TREE_VIEW_FRAME = "treeViewFrame"; public static final String QUERY_TREE_VIEW_ACTION = "QueryTreeView.do"; public static final String QUERY_GRID_VIEW_ACTION = "QueryGridView.do"; public static final String NO_OF_TREES = "noOfTrees"; public static final String PAGEOF_QUERY_MODULE = "pageOfQueryModule"; public static final String TREE_ROOTS = "treeRoots"; // Frame names in Query Module Results page.--ends here public static final String MAX_IDENTIFIER = "maxIdentifier"; public static final String AND_JOIN_CONDITION = "AND"; public static final String OR_JOIN_CONDITION = "OR"; //Sri: Changed the format for displaying in Specimen Event list (#463) public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm"; public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd"; // Mandar: Used for Date Validations in Validator Class public static final String DATE_SEPARATOR = "-"; public static final String DATE_SEPARATOR_DOT = "."; public static final String MIN_YEAR = "1900"; public static final String MAX_YEAR = "9999"; public static final String VIEW = "view"; public static final String DELETE = "delete"; public static final String EXPORT = "export"; public static final String SHOPPING_CART_ADD = "shoppingCartAdd"; public static final String SHOPPING_CART_DELETE = "shoppingCartDelete"; public static final String SHOPPING_CART_EXPORT = "shoppingCartExport"; public static final String NEWUSERFORM = "newUserForm"; public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect"; public static final String CALLED_FROM = "calledFrom"; public static final String ACCESS = "access"; //Constants required for Forgot Password public static final String FORGOT_PASSWORD = "forgotpassword"; public static final String LOGINNAME = "loginName"; public static final String LASTNAME = "lastName"; public static final String FIRSTNAME = "firstName"; public static final String INSTITUTION = "institution"; public static final String EMAIL = "email"; public static final String DEPARTMENT = "department"; public static final String ADDRESS = "address"; public static final String CITY = "city"; public static final String STATE = "state"; public static final String COUNTRY = "country"; public static final String NEXT_CONTAINER_NO = "startNumber"; public static final String CSM_USER_ID = "csmUserId"; public static final String INSTITUTIONLIST = "institutionList"; public static final String DEPARTMENTLIST = "departmentList"; public static final String STATELIST = "stateList"; public static final String COUNTRYLIST = "countryList"; public static final String ROLELIST = "roleList"; public static final String ROLEIDLIST = "roleIdList"; public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList"; public static final String GENDER_LIST = "genderList"; public static final String GENOTYPE_LIST = "genotypeList"; public static final String ETHNICITY_LIST = "ethnicityList"; public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList"; public static final String RACELIST = "raceList"; public static final String VITAL_STATUS_LIST = "vitalStatusList"; public static final String PARTICIPANT_LIST = "participantList"; public static final String PARTICIPANT_ID_LIST = "participantIdList"; public static final String PROTOCOL_LIST = "protocolList"; public static final String TIMEHOURLIST = "timeHourList"; public static final String TIMEMINUTESLIST = "timeMinutesList"; public static final String TIMEAMPMLIST = "timeAMPMList"; public static final String RECEIVEDBYLIST = "receivedByList"; public static final String COLLECTEDBYLIST = "collectedByList"; public static final String COLLECTIONSITELIST = "collectionSiteList"; public static final String RECEIVEDSITELIST = "receivedSiteList"; public static final String RECEIVEDMODELIST = "receivedModeList"; public static final String ACTIVITYSTATUSLIST = "activityStatusList"; public static final String USERLIST = "userList"; public static final String SITETYPELIST = "siteTypeList"; public static final String STORAGETYPELIST="storageTypeList"; public static final String STORAGECONTAINERLIST="storageContainerList"; public static final String SITELIST="siteList"; // public static final String SITEIDLIST="siteIdList"; public static final String USERIDLIST = "userIdList"; public static final String STORAGETYPEIDLIST="storageTypeIdList"; public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList"; public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant"; public static final String APPROVE_USER_STATUS_LIST = "statusList"; public static final String EVENT_PARAMETERS_LIST = "eventParametersList"; //New Specimen lists. public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList"; public static final String SPECIMEN_TYPE_LIST = "specimenTypeList"; public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList"; public static final String TISSUE_SITE_LIST = "tissueSiteList"; public static final String TISSUE_SIDE_LIST = "tissueSideList"; public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList"; public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList"; public static final String BIOHAZARD_NAME_LIST = "biohazardNameList"; public static final String BIOHAZARD_ID_LIST = "biohazardIdList"; public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList"; public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList"; public static final String RECEIVED_QUALITY_LIST = "receivedQualityList"; public static final String SPECIMEN_COLL_GP_NAME = "specimenCollectionGroupName"; //SpecimenCollecionGroup lists. public static final String PROTOCOL_TITLE_LIST = "protocolTitleList"; public static final String PARTICIPANT_NAME_LIST = "participantNameList"; public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList"; //public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList"; public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList"; //public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList"; public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray"; //public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray"; public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId"; public static final String REQ_PATH = "redirectTo"; public static final String CLINICAL_STATUS_LIST = "cinicalStatusList"; public static final String SPECIMEN_CLASS_LIST = "specimenClassList"; public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList"; public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap"; //Simple Query Interface Lists public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList"; public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle"; public static final String MAP_OF_STORAGE_CONTAINERS = "storageContainerMap"; public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject"; public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus"; public static final String START_NUMBER = "startNumber"; public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerIds"; public static final int STORAGE_CONTAINER_FIRST_ROW = 1; public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1; public static final String MAP_COLLECTION_PROTOCOL_LIST = "collectionProtocolList"; public static final String MAP_SPECIMEN_CLASS_LIST = "specimenClassList"; //event parameters lists public static final String METHOD_LIST = "methodList"; public static final String HOUR_LIST = "hourList"; public static final String MINUTES_LIST = "minutesList"; public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList"; public static final String PROCEDURE_LIST = "procedureList"; public static final String PROCEDUREIDLIST = "procedureIdList"; public static final String CONTAINER_LIST = "containerList"; public static final String CONTAINERIDLIST = "containerIdList"; public static final String FROMCONTAINERLIST="fromContainerList"; public static final String TOCONTAINERLIST="toContainerList"; public static final String FIXATION_LIST = "fixationList"; public static final String FROM_SITE_LIST="fromsiteList"; public static final String TO_SITE_LIST="tositeList"; public static final String ITEMLIST="itemList"; public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList"; public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList"; public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList"; public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList"; public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList"; public static final String STORAGE_STATUS_LIST="storageStatusList"; public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList"; public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList"; //For Specimen Event Parameters. public static final String SPECIMEN_ID = "specimenId"; public static final String FROM_POSITION_DATA = "fromPositionData"; public static final String POS_ONE ="posOne"; public static final String POS_TWO ="posTwo"; public static final String STORAGE_CONTAINER_ID ="storContId"; public static final String IS_RNA = "isRNA"; public static final String RNA = "RNA"; // New Participant Event Parameters public static final String PARTICIPANT_ID="participantId"; //Constants required in User.jsp Page public static final String USER_SEARCH_ACTION = "UserSearch.do"; public static final String USER_ADD_ACTION = "UserAdd.do"; public static final String USER_EDIT_ACTION = "UserEdit.do"; public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do"; public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do"; public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do"; public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do"; public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do"; //Constants required in Accession.jsp Page public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do"; public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do"; public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do"; //Constants required in StorageType.jsp Page public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do"; public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do"; public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do"; //Constants required in StorageContainer.jsp Page public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do"; public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do"; public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do"; public static final String HOLDS_LIST1 = "HoldsList1"; public static final String HOLDS_LIST2 = "HoldsList2"; public static final String HOLDS_LIST3 = "HoldsList3"; //Constants required in Site.jsp Page public static final String SITE_SEARCH_ACTION = "SiteSearch.do"; public static final String SITE_ADD_ACTION = "SiteAdd.do"; public static final String SITE_EDIT_ACTION = "SiteEdit.do"; //Constants required in Site.jsp Page public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do"; public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do"; public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do"; //Constants required in Partcipant.jsp Page public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do"; public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do"; public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do"; public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do"; public static final String PARTICIPANT_CONSENT_ENTER_RESPONSE= "Enter Response"; public static final String PARTICIPANT_CONSENT_EDIT_RESPONSE= "Edit Response"; //Constants required in Institution.jsp Page public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do"; public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do"; public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do"; //Constants required in Department.jsp Page public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do"; public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do"; public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do"; //Constants required in CollectionProtocolRegistration.jsp Page public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do"; public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do"; public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do"; //Constants required in CancerResearchGroup.jsp Page public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do"; public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do"; public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do"; //Constants required for Approve user public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do"; public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do"; //Reported Problem Constants public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do"; public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do"; public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do"; public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do"; //Query Results view Actions public static final String TREE_VIEW_ACTION = "TreeView.do"; public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do"; public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17"; //New Specimen Data Actions. public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do"; public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do"; public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do"; public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //Create Specimen Data Actions. public static final String CREATE_SPECIMEN_ADD_ACTION = "AddSpecimen.do"; public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do"; public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do"; //ShoppingCart Actions. public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do"; public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do"; public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do"; public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do"; //Constants required in FrozenEventParameters.jsp Page public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do"; public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do"; public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do"; //Constants required in CheckInCheckOutEventParameters.jsp Page public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do"; public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do"; //Constants required in ReceivedEventParameters.jsp Page public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do"; public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do"; public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do"; //Constants required in FluidSpecimenReviewEventParameters.jsp Page public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do"; public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do"; //Constants required in CELLSPECIMENREVIEWParameters.jsp Page public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do"; public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do"; //Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do"; public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do"; // Constants required in DisposalEventParameters.jsp Page public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do"; public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do"; public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do"; // Constants required in ThawEventParameters.jsp Page public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do"; public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do"; public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do"; // Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do"; public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do"; // Constants required in CollectionEventParameters.jsp Page public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do"; public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do"; public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do"; // Constants required in SpunEventParameters.jsp Page public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do"; public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do"; public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do"; // Constants required in EmbeddedEventParameters.jsp Page public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do"; public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do"; public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do"; // Constants required in TransferEventParameters.jsp Page public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do"; public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do"; public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do"; // Constants required in FixedEventParameters.jsp Page public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do"; public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do"; public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do"; // Constants required in ProcedureEventParameters.jsp Page public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do"; public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do"; public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do"; // Constants required in Distribution.jsp Page public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do"; public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do"; public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do"; public static final String SPECIMENARRAYTYPE_ADD_ACTION = "SpecimenArrayTypeAdd.do?operation=add"; public static final String SPECIMENARRAYTYPE_EDIT_ACTION = "SpecimenArrayTypeEdit.do?operation=edit"; public static final String ARRAY_DISTRIBUTION_ADD_ACTION = "ArrayDistributionAdd.do"; public static final String SPECIMENARRAY_ADD_ACTION = "SpecimenArrayAdd.do"; public static final String SPECIMENARRAY_EDIT_ACTION = "SpecimenArrayEdit.do"; //Spreadsheet Export Action public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do"; //Aliquots Action public static final String ALIQUOT_ACTION = "Aliquots.do"; public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do"; public static final String ALIQUOT_SUMMARY_ACTION = "AliquotSummary.do"; //Constants related to Aliquots functionality public static final String PAGEOF_ALIQUOT = "pageOfAliquot"; public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot"; public static final String PAGEOF_ALIQUOT_SUMMARY = "pageOfAliquotSummary"; public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap"; public static final String COMMON_ADD_EDIT = "commonAddEdit"; //Constants related to SpecimenArrayAliquots functionality public static final String STORAGE_TYPE_ID="storageTypeId"; public static final String ALIQUOT_SPECIMEN_ARRAY_TYPE="SpecimenArrayType"; public static final String ALIQUOT_SPECIMEN_CLASS="SpecimenClass"; public static final String ALIQUOT_SPECIMEN_TYPES="SpecimenTypes"; public static final String ALIQUOT_ALIQUOT_COUNTS="AliquotCounts"; //Specimen Array Aliquots pages public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT = "pageOfSpecimenArrayAliquot"; public static final String PAGEOF_SPECIMEN_ARRAY_CREATE_ALIQUOT = "pageOfSpecimenArrayCreateAliquot"; public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT_SUMMARY = "pageOfSpecimenArrayAliquotSummary"; //Specimen Array Aliquots Action public static final String SPECIMEN_ARRAY_ALIQUOT_ACTION = "SpecimenArrayAliquots.do"; public static final String SPECIMEN_ARRAY_CREATE_ALIQUOT_ACTION = "SpecimenArrayCreateAliquots.do"; //Constants related to QuickEvents functionality public static final String QUICKEVENTS_ACTION = "QuickEventsSearch.do"; public static final String QUICKEVENTSPARAMETERS_ACTION = "ListSpecimenEventParameters.do"; //SimilarContainers Action public static final String SIMILAR_CONTAINERS_ACTION = "SimilarContainers.do"; public static final String CREATE_SIMILAR_CONTAINERS_ACTION = "CreateSimilarContainers.do"; public static final String SIMILAR_CONTAINERS_ADD_ACTION = "SimilarContainersAdd.do"; //Constants related to Similar Containsers public static final String PAGEOF_SIMILAR_CONTAINERS = "pageOfSimilarContainers"; public static final String PAGEOF_CREATE_SIMILAR_CONTAINERS = "pageOfCreateSimilarContainers"; public static final String PAGEOF_STORAGE_CONTAINER = "pageOfStorageContainer"; //Levels of nodes in query results tree. public static final int MAX_LEVEL = 5; public static final int MIN_LEVEL = 1; public static final String TABLE_NAME_COLUMN = "TABLE_NAME"; //Spreadsheet view Constants in DataViewAction. public static final String PARTICIPANT = "Participant"; public static final String ACCESSION = "Accession"; public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?id="; public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do"; public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?id="; public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do"; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?id="; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do"; public static final String QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "QuerySpecimenCollectionGroupAdd.do"; public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?id="; public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do"; //public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?id="; public static final String SPECIMEN = "Specimen"; public static final String SEGMENT = "Segment"; public static final String SAMPLE = "Sample"; public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration"; public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID"; public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID"; public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID"; public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID"; public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID"; //For getting the tables for Simple Query and Fcon Query. public static final int ADVANCE_QUERY_TABLES = 2; //Identifiers for various Form beans public static final int DEFAULT_BIZ_LOGIC = 0; public static final int USER_FORM_ID = 1; public static final int ACCESSION_FORM_ID = 3; public static final int REPORTED_PROBLEM_FORM_ID = 4; public static final int INSTITUTION_FORM_ID = 5; public static final int APPROVE_USER_FORM_ID = 6; public static final int ACTIVITY_STATUS_FORM_ID = 7; public static final int DEPARTMENT_FORM_ID = 8; public static final int COLLECTION_PROTOCOL_FORM_ID = 9; public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10; public static final int STORAGE_CONTAINER_FORM_ID = 11; public static final int STORAGE_TYPE_FORM_ID = 12; public static final int SITE_FORM_ID = 13; public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14; public static final int BIOHAZARD_FORM_ID = 15; public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16; public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17; public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18; public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21; public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23; public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24; public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25; public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26; public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27; public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28; public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29; public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30; public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31; public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32; public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33; public static final int CREATE_SPECIMEN_FORM_ID = 34; public static final int FORGOT_PASSWORD_FORM_ID = 35; public static final int SIGNUP_FORM_ID = 36; public static final int DISTRIBUTION_FORM_ID = 37; public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38; public static final int SHOPPING_CART_FORM_ID = 39; public static final int CONFIGURE_RESULT_VIEW_ID = 41; public static final int ADVANCE_QUERY_INTERFACE_ID = 42; public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19; public static final int PARTICIPANT_FORM_ID = 2; public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20; public static final int NEW_SPECIMEN_FORM_ID = 22; public static final int ALIQUOT_FORM_ID = 44; public static final int QUICKEVENTS_FORM_ID = 45; public static final int LIST_SPECIMEN_EVENT_PARAMETERS_FORM_ID = 46; public static final int SIMILAR_CONTAINERS_FORM_ID = 47; // chetan (13-07-2006) public static final int SPECIMEN_ARRAY_TYPE_FORM_ID = 48; public static final int ARRAY_DISTRIBUTION_FORM_ID = 49; public static final int SPECIMEN_ARRAY_FORM_ID = 50; public static final int SPECIMEN_ARRAY_ALIQUOT_FORM_ID = 51; public static final int ASSIGN_PRIVILEGE_FORM_ID = 52; public static final int CDE_FORM_ID = 53; public static final int MULTIPLE_SPECIMEN_STOGAGE_LOCATION_FORM_ID = 54; public static final int REQUEST_LIST_FILTERATION_FORM_ID = 55; public static final int ORDER_FORM_ID = 56; public static final int ORDER_ARRAY_FORM_ID = 57; public static final int REQUEST_DETAILS_FORM_ID = 64; public static final int ORDER_PATHOLOGY_FORM_ID = 58; public static final int NEW_PATHOLOGY_FORM_ID=59; public static final int DEIDENTIFIED_SURGICAL_PATHOLOGY_REPORT_FORM_ID=60; public static final int PATHOLOGY_REPORT_REVIEW_FORM_ID=61; public static final int QUARANTINE_EVENT_PARAMETER_FORM_ID=62; public static final int CONSENT_FORM_ID=63; //Misc public static final String SEPARATOR = " : "; //Identifiers for JDBC DAO. public static final int QUERY_RESULT_TREE_JDBC_DAO = 1; //Activity Status values public static final String ACTIVITY_STATUS_APPROVE = "Approve"; public static final String ACTIVITY_STATUS_REJECT = "Reject"; public static final String ACTIVITY_STATUS_NEW = "New"; public static final String ACTIVITY_STATUS_PENDING = "Pending"; //Approve User status values. public static final String APPROVE_USER_APPROVE_STATUS = "Approve"; public static final String APPROVE_USER_REJECT_STATUS = "Reject"; public static final String APPROVE_USER_PENDING_STATUS = "Pending"; //Approve User Constants public static final int ZERO = 0; public static final int START_PAGE = 1; public static final int NUMBER_RESULTS_PER_PAGE = 20; public static final int NUMBER_RESULTS_PER_PAGE_SEARCH = 15; public static final String PAGE_NUMBER = "pageNum"; public static final String RESULTS_PER_PAGE = "numResultsPerPage"; public static final String TOTAL_RESULTS = "totalResults"; public static final String PREVIOUS_PAGE = "prevpage"; public static final String NEXT_PAGE = "nextPage"; public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList"; public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList"; public static final String USER_DETAILS = "details"; public static final String CURRENT_RECORD = "currentRecord"; public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core."; //Query Interface Results View Constants public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser"; public static final String PAGEOF_SIGNUP = "pageOfSignUp"; public static final String PAGEOF_USERADD = "pageOfUserAdd"; public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin"; public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile"; public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword"; //For Simple Query Interface and Edit. public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject"; //Query results view temporary table columns. public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID"; public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID"; public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID"; public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID"; public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE"; // Assign Privilege Constants. public static final boolean PRIVILEGE_DEASSIGN = false; public static final String OPERATION_DISALLOW = "Disallow"; //Constants for default column names to be shown for query result. public static final String[] DEFAULT_SPREADSHEET_COLUMNS = { // QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID, // QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID, // QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE "IDENTIFIER","TYPE","ONE_DIMENSION_LABEL" }; //Query results edit constants - MakeEditableAction. public static final String EDITABLE = "editable"; //URL paths for Applet in TreeView.jsp public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class"; public static final String APPLET_CODEBASE = "Applet"; //Shopping Cart public static final String SHOPPING_CART = "shoppingCart"; public static final String QUERY_SHOPPING_CART = "queryShoppingCart"; public static final int SELECT_OPTION_VALUE = -1; public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"}; // Constants required in CollectionProtocol.jsp Page public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do"; public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do"; public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do"; // Constants required in DistributionProtocol.jsp Page public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do"; public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do"; public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do"; public static final String [] ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed", "Disabled" }; public static final String [] SITE_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] USER_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Active", "Closed" }; public static final String [] APPROVE_USER_STATUS_VALUES = { SELECT_OPTION, APPROVE_USER_APPROVE_STATUS, APPROVE_USER_REJECT_STATUS, APPROVE_USER_PENDING_STATUS, }; public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = { SELECT_OPTION, "Closed", "Pending" }; public static final String [] DISPOSAL_EVENT_ACTIVITY_STATUS_VALUES = { "Closed", "Disabled" }; public static final String TISSUE = "Tissue"; public static final String FLUID = "Fluid"; public static final String CELL = "Cell"; public static final String MOLECULAR = "Molecular"; public static final String [] SPECIMEN_TYPE_VALUES = { SELECT_OPTION, TISSUE, FLUID, CELL, MOLECULAR }; public static final String [] HOUR_ARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public static final String [] MINUTES_ARRAY = { "00", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public static final String UNIT_GM = "gm"; public static final String UNIT_ML = "ml"; public static final String UNIT_CC = "cell count"; public static final String UNIT_MG = "g"; public static final String UNIT_CN = "count"; public static final String UNIT_CL = "cells"; public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status"; public static final String CDE_NAME_GENDER = "Gender"; public static final String CDE_NAME_GENOTYPE = "Genotype"; public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen"; public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type"; public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side"; public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status"; public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality"; public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type"; public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure"; public static final String CDE_NAME_CONTAINER = "Container"; public static final String CDE_NAME_METHOD = "Method"; public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium"; public static final String CDE_NAME_BIOHAZARD = "Biohazard"; public static final String CDE_NAME_ETHNICITY = "Ethnicity"; public static final String CDE_NAME_RACE = "Race"; public static final String CDE_VITAL_STATUS = "Vital Status"; public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis"; public static final String CDE_NAME_SITE_TYPE = "Site Type"; public static final String CDE_NAME_COUNTRY_LIST = "Countries"; public static final String CDE_NAME_STATE_LIST = "States"; public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality"; //Constants for Advanced Search public static final String STRING_OPERATORS = "StringOperators"; public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators"; public static final String ENUMERATED_OPERATORS = "EnumeratedOperators"; public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators"; public static final String [] STORAGE_STATUS_ARRAY = { SELECT_OPTION, "CHECK IN", "CHECK OUT" }; // constants for Data required in query public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames"; public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER"; public static final String NAME = "name"; public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION, "Cell Specimen Review", "Check In Check Out", "Collection", "Disposal", "Embedded", "Fixed", "Fluid Specimen Review", "Frozen", "Molecular Specimen Review", "Procedure", "Received", "Spun", "Thaw", "Tissue Specimen Review", "Transfer" }; public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier", "Event Parameter", "User", "Date / Time", "PageOf"}; public static final String DERIVED_SPECIMEN_COLUMNS[] = { "Label", "Class", "Type", "Quantity", "rowSelected"}; public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier", "Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"}; //Constants required in AssignPrivileges.jsp public static final String ASSIGN = "assignOperation"; public static final String PRIVILEGES = "privileges"; public static final String OBJECT_TYPES = "objectTypes"; public static final String OBJECT_TYPE_VALUES = "objectTypeValues"; public static final String RECORD_IDS = "recordIds"; public static final String ATTRIBUTES = "attributes"; public static final String GROUPS = "groups"; public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege"; public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege"; public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do"; public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2; /** * @param id * @return */ public static String getUserPGName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } /** * @param id * @return */ public static String getUserGroupName(Long identifier) { if(identifier == null) { return "USER_"; } return "USER_"+identifier; } //Mandar 25-Apr-06 : bug 1414 : Tissue units as per type // tissue types with unit= count public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK public static final String NOT_SPECIFIED = "Not Specified"; public static final String WITHDRAWN = "Withdrawn"; // tissue types with unit= g public static final String FRESH_TISSUE = "Fresh Tissue"; public static final String FROZEN_TISSUE = "Frozen Tissue"; public static final String FIXED_TISSUE = "Fixed Tissue"; public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide"; //tissue types with unit= cc public static final String MICRODISSECTED = "Microdissected"; // constants required for Distribution Report public static final String CONFIGURATION_TABLES = "configurationTables"; public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen", "SpecimenCollectionGroup","DistributedItem"}; public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap"; public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do"; public static final String TABLE_NAMES_LIST = "tableNamesList"; public static final String COLUMN_NAMES_LIST = "columnNamesList"; public static final String SPECIMEN_COLUMN_NAMES_LIST = "specimenColumnNamesList"; public static final String DISTRIBUTION_ID = "distributionId"; public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do"; public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do"; public static final String ARRAY_DISTRIBUTION_REPORT_ACTION = "ArrayDistributionReport.do"; public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do"; public static final String ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="ArrayDistributionReportSave.do"; //bug#4981 :kalpana public static final String SELECTED_COLUMNS[] = {"Specimen.LABEL.Label : Specimen", "Specimen.TYPE.Type : Specimen", "SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen", "SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen", "Specimen.PATHOLOGICAL_STATUS.Pathological Status : Specimen", "DistributedItem.QUANTITY.Quantity : Distribution"}; //"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen", public static final String SPECIMEN_IN_ARRAY_SELECTED_COLUMNS[] = { "Specimen.LABEL.Label : Specimen", "Specimen.BARCODE.barcode : Specimen", "SpecimenArrayContent.PositionDimensionOne.PositionDimensionOne : Specimen", "SpecimenArrayContent.PositionDimensionTwo.PositionDimensionTwo : Specimen", "Specimen.CLASS.CLASS : Specimen", "Specimen.TYPE.Type : Specimen", "SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen", "SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen", }; public static final String ARRAY_SELECTED_COLUMNS[] = { "SpecimenArray.Name.Name : SpecimenArray", "Container.barcode.Barcode : SpecimenArray", "ContainerType.name.ArrayType : ContainerType", "Container.PositionDimensionOne.Position One: Container", "Container.PositionDimensionTwo.Position Two: Container", "Container.CapacityOne.Dimension One: Container", "Container.CapacityTwo.Dimension Two: Container", "ContainerType.SpecimenClass.specimen class : ContainerType", "ContainerType.SpecimenTypes.specimen Types : ContainerType", "Container.Comment.comment: Container", }; public static final String SPECIMEN_ID_LIST = "specimenIdList"; public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution"; public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv"; public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm"; public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData"; public static final String DISTRIBUTED_ITEM = "DistributedItem"; //constants for Simple Query Interface Configuration public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do"; public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do"; public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do"; public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do"; public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do"; public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution"; public static final String RESULT_VIEW_VECTOR = "resultViewVector"; public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute"; //public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount"; public static final String UNDEFINED = "Undefined"; public static final String UNKNOWN = "Unknown"; public static final String UNSPECIFIED = "Unspecified"; public static final String NOTSPECIFIED = "Not Specified"; public static final String SEARCH_RESULT = "SearchResult.csv"; // Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587 // public static final String ODD_COLOR = "#FEFB85"; // public static final String EVEN_COLOR = "#A7FEAB"; // Light and dark shades of GREY. public static final String ODD_COLOR = "#E5E5E5"; public static final String EVEN_COLOR = "#F7F7F7"; // TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do"; public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do"; public static final String PARENT_SPECIMEN_ID = "parentSpecimenId"; public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId"; public static final String FORWARDLIST = "forwardToList"; public static final String [][] SPECIMEN_FORWARD_TO_LIST = { {"Submit", "success"}, {"Derive", "createNew"}, {"Add Events", "eventParameters"}, {"More", "sameCollectionGroup"}, {"Distribute", "distribution" } }; public static final String [] SPECIMEN_BUTTON_TIPS = { "Submit only", "Submit and derive", "Submit and add events", "Submit and add more to same group", "Submit and distribute" }; public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = { {"Submit", "success"}, {"Add Specimen", "createNewSpecimen"}, {"Add Multiple Specimens", "createMultipleSpecimen"} }; public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = { {"Submit", "success"}, {"Specimen Collection Group", "createSpecimenCollectionGroup"} }; public static final String [][] PARTICIPANT_FORWARD_TO_LIST = { {"Submit", "success"}, {"Submit", "createParticipantRegistration"}, {"Specimen Collection Group", "specimenCollectionGroup"}, {"Submit", "pageOfParticipantCPQuery"} }; public static final String [][] STORAGE_TYPE_FORWARD_TO_LIST = { {"Submit", "success"}, {"Add Container", "storageContainer"} }; //Constants Required for Advance Search //Tree related //public static final String PARTICIPANT ='Participant'; public static final String[] ADVANCE_QUERY_TREE_HEIRARCHY={ //Represents the Advance Query tree Heirarchy. Constants.PARTICIPANT, Constants.COLLECTION_PROTOCOL, Constants.SPECIMEN_COLLECTION_GROUP, Constants.SPECIMEN }; public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol"; public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group"; public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol"; public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup"; public static final String DISTRIBUTION = "Distribution"; public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String CP = "CP"; public static final String SCG = "SCG"; public static final String D = "D"; public static final String DP = "DP"; public static final String C = "C"; public static final String S = "S"; public static final String P = "P"; public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView"; public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do"; public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do"; public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do"; public static final String ADVANCED_QUERY_ADD = "Add"; public static final String ADVANCED_QUERY_EDIT = "Edit"; public static final String ADVANCED_QUERY_DELETE = "Delete"; public static final String ADVANCED_QUERY_OPERATOR = "Operator"; public static final String ADVANCED_QUERY_OR = "OR"; public static final String ADVANCED_QUERY_AND = "pAND"; public static final String EVENT_CONDITIONS = "eventConditions"; public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap"; public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit"; public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit"; public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit"; public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit"; public static final String PARTICIPANT_COLUMNS = "particpantColumns"; public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns"; public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns"; public static final String SPECIMEN_COLUMNS = "SpecimenColumns"; public static final String USER_ID_COLUMN = "USER_ID"; public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain"; //Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic public static final boolean IS_AUDITABLE_TRUE = true; public static final boolean IS_SECURE_UPDATE_TRUE = true; public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false; //Constants for HTTP-API public static final String CONTENT_TYPE = "CONTENT-TYPE"; // For StorageContainer isFull status public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList"; public static final String [] IS_CONTAINER_FULL_VALUES = { SELECT_OPTION, "True", "False" }; public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel"; public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel"; // public static final String SPECIMEN_TYPE_TISSUE = "Tissue"; // public static final String SPECIMEN_TYPE_FLUID = "Fluid"; // public static final String SPECIMEN_TYPE_CELL = "Cell"; // public static final String SPECIMEN_TYPE_MOL = "Molecular"; public static final String SPECIMEN_TYPE_COUNT = "Count"; public static final String SPECIMEN_TYPE_QUANTITY = "Quantity"; public static final String SPECIMEN_TYPE_DETAILS = "Details"; public static final String SPECIMEN_COUNT = "totalSpecimenCount"; public static final String TOTAL = "Total"; public static final String SPECIMENS = "Specimens"; //User Roles public static final String TECHNICIAN = "Technician"; public static final String SUPERVISOR = "Supervisor"; public static final String SCIENTIST = "Scientist"; public static final String CHILD_CONTAINER_TYPE = "childContainerType"; public static final String UNUSED = "Unused"; public static final String TYPE = "Type"; //Mandar: 28-Apr-06 Bug 1129 public static final String DUPLICATE_SPECIMEN="duplicateSpecimen"; //Constants required in ParticipantLookupAction public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter"; public static final String PARTICIPANT_LOOKUP_CUTOFF="lookup.cutoff"; public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo"; public static final String PARTICIPANT_LOOKUP_SUCCESS="success"; public static final String PARTICIPANT_ADD_FORWARD="participantAdd"; public static final String PARTICIPANT_SYSTEM_IDENTIFIER="IDENTIFIER"; public static final String PARTICIPANT_LAST_NAME="LAST_NAME"; public static final String PARTICIPANT_FIRST_NAME="FIRST_NAME"; public static final String PARTICIPANT_MIDDLE_NAME="MIDDLE_NAME"; public static final String PARTICIPANT_BIRTH_DATE="BIRTH_DATE"; public static final String PARTICIPANT_DEATH_DATE="DEATH_DATE"; public static final String PARTICIPANT_VITAL_STATUS="VITAL_STATUS"; public static final String PARTICIPANT_GENDER="GENDER"; public static final String PARTICIPANT_SEX_GENOTYPE="SEX_GENOTYPE"; public static final String PARTICIPANT_RACE="RACE"; public static final String PARTICIPANT_ETHINICITY="ETHINICITY"; public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SOCIAL_SECURITY_NUMBER"; public static final String PARTICIPANT_PROBABLITY_MATCH="Probability"; public static final String PARTICIPANT_MEDICAL_RECORD_NO="MEDICAL_RECORD_NUMBER"; public static final String PARTICIPANT_SSN_EXACT="SSNExact"; public static final String PARTICIPANT_SSN_PARTIAL="SSNPartial"; public static final String PARTICIPANT_PMI_EXACT="PMIExact"; public static final String PARTICIPANT_PMI_PARTIAL="PMIPartial"; public static final String PARTICIPANT_DOB_EXACT="DOBExact"; public static final String PARTICIPANT_DOB_PARTIAL="DOBPartial"; public static final String PARTICIPANT_LAST_NAME_EXACT="LastNameExact"; public static final String PARTICIPANT_LAST_NAME_PARTIAL="LastNamePartial"; public static final String PARTICIPANT_FIRST_NAME_EXACT="NameExact"; public static final String PARTICIPANT_FIRST_NAME_PARTIAL="NamePartial"; public static final String PARTICIPANT_MIDDLE_NAME_EXACT="MiddleNameExact"; public static final String PARTICIPANT_MIDDLE_NAME_PARTIAL="MiddleNamePartial"; public static final String PARTICIPANT_GENDER_EXACT="GenderExact"; public static final String PARTICIPANT_RACE_EXACT="RaceExact"; public static final String PARTICIPANT_RACE_PARTIAL="RacePartial"; public static final String PARTICIPANT_BONUS="Bonus"; public static final String PARTICIPANT_TOTAL_POINTS="TotalPoints"; public static final String PARTICIPANT_MATCH_CHARACTERS_FOR_LAST_NAME="MatchCharactersForLastName"; //Constants for integration of caTies and CAE with caTissue Core public static final String LINKED_DATA = "linkedData"; public static final String APPLICATION_ID = "applicationId"; public static final String CATIES = "caTies"; public static final String CAE = "cae"; public static final String EDIT_TAB_LINK = "editTabLink"; public static final String CATIES_PUBLIC_SERVER_NAME = "CaTiesPublicServerName"; public static final String CATIES_PRIVATE_SERVER_NAME = "CaTiesPrivateServerName"; //Constants for StorageContainerMap Applet public static final String CONTAINER_STYLEID = "containerStyleId"; public static final String CONTAINER_STYLE = "containerStyle"; public static final String XDIM_STYLEID = "xDimStyleId"; public static final String YDIM_STYLEID = "yDimStyleId"; public static final String SELECTED_CONTAINER_NAME="selectedContainerName"; public static final String CONTAINERID="containerId"; public static final String POS1="pos1"; public static final String POS2="pos2"; //Constants for QuickEvents public static final String EVENT_SELECTED = "eventSelected"; //Constant for SpecimenEvents page. public static final String EVENTS_TITLE_MESSAGE = "Existing events for the specimen with label {0}"; public static final String SURGICAL_PATHOLOGY_REPORT = "Surgical Pathology Report"; public static final String CLINICAL_ANNOTATIONS = "Clinical Annotations"; //Constants for Specimen Collection Group name- new field public static final String RESET_NAME ="resetName"; // Labels for Storage Containers public static final String[] STORAGE_CONTAINER_LABEL = {" Name"," Pos1"," Pos2"}; //Constans for Any field public static final String HOLDS_ANY = "--All //Constants : Specimen -> lineage public static final String NEW_SPECIMEN = "New"; public static final String DERIVED_SPECIMEN = "Derived"; public static final String ALIQUOT = "Aliquot"; //Constant for length of messageBody in Reported problem page public static final int messageLength= 500; public static final String NEXT_NUMBER="nextNumber"; // public static final String getCollectionProtocolPIGroupName(Long identifier) // if(identifier == null) // return "PI_COLLECTION_PROTOCOL_"; // return "PI_COLLECTION_PROTOCOL_"+identifier; // public static final String getCollectionProtocolCoordinatorGroupName(Long identifier) // if(identifier == null) // return "COORDINATORS_COLLECTION_PROTOCOL_"; // return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier; // public static final String getDistributionProtocolPIGroupName(Long identifier) // if(identifier == null) // return "PI_DISTRIBUTION_PROTOCOL_"; // return "PI_DISTRIBUTION_PROTOCOL_"+identifier; // public static final String getCollectionProtocolPGName(Long identifier) // if(identifier == null) // return "COLLECTION_PROTOCOL_"; // return "COLLECTION_PROTOCOL_"+identifier; // public static final String getDistributionProtocolPGName(Long identifier) // if(identifier == null) // return "DISTRIBUTION_PROTOCOL_"; // return "DISTRIBUTION_PROTOCOL_"+identifier; public static final String ALL = "All"; //constant for pagination data list public static final String PAGINATION_DATA_LIST = "paginationDataList"; public static final int SPECIMEN_DISTRIBUTION_TYPE = 1; public static final int SPECIMEN_ARRAY_DISTRIBUTION_TYPE = 2; public static final int BARCODE_BASED_DISTRIBUTION = 1; public static final int LABEL_BASED_DISTRIBUTION = 2; public static final String DISTRIBUTION_TYPE_LIST = "DISTRIBUTION_TYPE_LIST"; public static final String DISTRIBUTION_BASED_ON = "DISTRIBUTION_BASED_ON"; public static final String SYSTEM_LABEL = "label"; public static final String SYSTEM_BARCODE = "barcode"; public static final String SYSTEM_NAME = "name"; //Mandar : 05Sep06 Array for multiple specimen field names public static final String DERIVED_OPERATION = "derivedOperation"; public static final String [] MULTIPLE_SPECIMEN_FIELD_NAMES = { "Collection Group", "Parent ID", "Name", "Barcode", "Class", "Type", "Tissue Site", "Tissue Side", "Pathological Status", "Concentration", "Quantity", "Storage Location", "Comments", "Events", "External Identifier", "Biohazards" // "Derived", // "Aliquots" }; public static final String PAGEOF_MULTIPLE_SPECIMEN = "pageOfMultipleSpecimen"; public static final String PAGEOF_MULTIPLE_SPECIMEN_MAIN = "pageOfMultipleSpecimenMain"; public static final String MULTIPLE_SPECIMEN_ACTION = "MultipleSpecimen.do"; public static final String INIT_MULTIPLE_SPECIMEN_ACTION = "InitMultipleSpecimen.do"; public static final String MULTIPLE_SPECIMEN_APPLET_ACTION = "MultipleSpecimenAppletAction.do"; public static final String NEW_MULTIPLE_SPECIMEN_ACTION = "NewMultipleSpecimenAction.do"; public static final String MULTIPLE_SPECIMEN_RESULT = "multipleSpecimenResult"; public static final String SAVED_SPECIMEN_COLLECTION = "savedSpecimenCollection"; public static final String [] MULTIPLE_SPECIMEN_FORM_FIELD_NAMES = { "CollectionGroup", "ParentID", "Name", "Barcode", "Class", "Type", "TissueSite", "TissueSide", "PathologicalStatus", "Concentration", "Quantity", "StorageLocation", "Comments", "Events", "ExternalIdentifier", "Biohazards" // "Derived", // "Aliquots" }; public static final String MULTIPLE_SPECIMEN_MAP_KEY = "MULTIPLE_SPECIMEN_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_EVENT_MAP_KEY = "MULTIPLE_SPECIMEN_EVENT_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY = "MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY = "MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY"; public static final String MULTIPLE_SPECIMEN_LABEL_MAP_KEY = "MULTIPLE_SPECIMEN_LABEL_MAP_KEY"; public static final String DERIVED_FORM = "DerivedForm"; public static final String SPECIMEN_ATTRIBUTE_KEY = "specimenAttributeKey"; public static final String SPECIMEN_CLASS = "specimenClass"; public static final String SPECIMEN_CALL_BACK_FUNCTION = "specimenCallBackFunction"; public static final String APPEND_COUNT = "_count"; public static final String EXTERNALIDENTIFIER_TYPE = "ExternalIdentifier"; public static final String BIOHAZARD_TYPE = "BioHazard"; public static final String COMMENTS_TYPE = "comments"; public static final String EVENTS_TYPE = "Events"; public static final String MULTIPLE_SPECIMEN_APPLET_NAME = "MultipleSpecimenApplet"; public static final String INPUT_APPLET_DATA = "inputAppletData"; // Start Specimen Array Applet related constants public static final String SPECIMEN_ARRAY_APPLET = "edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.class"; public static final String SPECIMEN_ARRAY_APPLET_NAME = "specimenArrayApplet"; public static final String SPECIMEN_ARRAY_CONTENT_KEY = "SpecimenArrayContentKey"; public static final String SPECIMEN_LABEL_COLUMN_NAME = "label"; public static final String SPECIMEN_BARCODE_COLUMN_NAME = "barcode"; public static final String ARRAY_SPECIMEN_DOES_NOT_EXIST_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!!specimen does not exist "; public static final String ARRAY_SPECIMEN_NOT_ACTIVE_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!! Specimen is closed/disabled "; public static final String ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE = "Specimen Array should contain at least one specimen"; public static final String ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE = "Please add compatible specimens to specimen array (belong to same specimen class & specimen types of Array)"; public static final String ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE = "Please enter quantity for Molecular Specimen /** * Specify the SPECIMEN_ARRAY_LIST as key for specimen array type list */ public static final String SPECIMEN_ARRAY_TYPE_LIST = "specimenArrayList"; public static final String SPECIMEN_ARRAY_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArray"; public static final String SPECIMEN_ARRAY_TYPE_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArrayType"; // End // Common Applet Constants public static final String APPLET_SERVER_HTTP_START_STR = "http: public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL"; public static final String IS_NOT_NULL = "is not null"; public static final String IS_NULL = "is null"; // Used in array action public static final String ARRAY_TYPE_ANY_VALUE = "2"; public static final String ARRAY_TYPE_ANY_NAME = "Any"; // end // Array Type All Id in table public static final short ARRAY_TYPE_ALL_ID = 2; // constants required for caching mechanism of ParticipantBizLogic public static final String MAP_OF_PARTICIPANTS = "listOfParticipants"; public static final String LIST_OF_REGISTRATION_INFO = "listOfParticipantRegistrations"; public static final String EHCACHE_FOR_CATISSUE_CORE = "cacheForCaTissueCore"; public static final String MAP_OF_DISABLED_CONTAINERS = "listOfDisabledContainers"; public static final String MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN = "listOfContainerForDisabledContainerSpecimen"; public static final String ADD = "add"; public static final String EDIT = "edit"; public static final String ID = "id"; public static final String MANAGE_BIO_SPECIMEN_ACTION = "/ManageBioSpecimen.do"; public static final String CREATE_PARTICIPANT_REGISTRATION = "createParticipantRegistration"; public static final String CREATE_PARTICIPANT_REGISTRATION_ADD = "createParticipantRegistrationAdd"; public static final String CREATE_PARTICIPANT_REGISTRATION_EDIT= "createParticipantRegistrationEdit"; public static final String CAN_HOLD_CONTAINER_TYPE = "holdContainerType"; public static final String CAN_HOLD_SPECIMEN_CLASS = "holdSpecimenClass"; public static final String CAN_HOLD_COLLECTION_PROTOCOL = "holdCollectionProtocol"; public static final String CAN_HOLD_SPECIMEN_ARRAY_TYPE = "holdSpecimenArrayType"; public static final String COLLECTION_PROTOCOL_ID = "collectionProtocolId"; public static final String SPECIMEN_CLASS_NAME = "specimeClassName"; public static final String ENABLE_STORAGE_CONTAINER_GRID_PAGE = "enablePage"; public static final int ALL_STORAGE_TYPE_ID = 1; //Constant for the "All" storage type, which can hold all container type public static final int ALL_SPECIMEN_ARRAY_TYPE_ID = 2;//Constant for the "All" storage type, which can hold all specimen array type public static final String SPECIMEN_LABEL_CONTAINER_MAP = "Specimen : "; public static final String CONTAINER_LABEL_CONTAINER_MAP = "Container : "; public static final String SPECIMEN_ARRAY_LABEL_CONTAINER_MAP = "Array : "; public static final String SPECIMEN_PROTOCOL ="SpecimenProtocol"; public static final String SPECIMEN_PROTOCOL_SHORT_TITLE ="SHORT_TITLE"; public static final String SPECIMEN_COLLECTION_GROUP_NAME ="NAME"; public static final String SPECIMEN_LABEL = "LABEL"; // Patch ID: Bug#3184_14 public static final String NUMBER_OF_SPECIMEN = "numberOfSpecimen"; //Constants required for max limit on no. of containers in the drop down public static final String CONTAINERS_MAX_LIMIT = "containers_max_limit"; public static final String EXCEEDS_MAX_LIMIT = "exceedsMaxLimit"; //MultipleSpecimen Constants public static final String MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE="multipleSpecimen.ColumnsPerPage"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="MultipleSpecimenStorageLocationAdd.do"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_AVAILABLE_MAP="locationMap"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_SPECIMEN_MAP= "specimenMap"; public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_KEY_SEPARATOR = "$"; public static final String PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "formSubmitted"; public static final String MULTIPLE_SPECIMEN_SUBMIT_SUCCESSFUL = "submitSuccessful"; public static final String MULTIPLE_SPECIMEN_SPECIMEN_ORDER_LIST= "specimenOrderList"; public static final String MULTIPLE_SPECIMEN_DELETELAST_SPECIMEN_ID = "SpecimenId"; public static final String MULTIPLE_SPECIMEN_PARENT_COLLECTION_GROUP = "ParentSpecimenCollectionGroup"; public static final String NO_OF_RECORDS_PER_PAGE="resultView.noOfRecordsPerPage"; /** * Name: Prafull * Description: Query performance issue. Instead of saving complete query results in session, resultd will be fetched for each result page navigation. * object of class QuerySessionData will be saved session, which will contain the required information for query execution while navigating through query result pages. * Changes resultper page options, removed 5000 from the array & added 500 as another option. */ public static final int[] RESULT_PERPAGE_OPTIONS = {10,50,100,500,1000}; /** * Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action. */ public static final String SPECIMEN_MAP_KEY = "Specimen_derived_map_key"; /** * Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action. */ public static final String CONTAINER_MAP_KEY = "container_map_key"; /** * Used to saperate storage container, xPos, yPos */ public static final String STORAGE_LOCATION_SAPERATOR = "@"; public static final String METHOD_NAME="method"; public static final String GRID_FOR_EVENTS="eventParameter"; public static final String GRID_FOR_EDIT_SEARCH="editSearch"; public static final String GRID_FOR_DERIVED_SPECIMEN="derivedSpecimen"; //CpBasedSearch Constants public static final String CP_QUERY = "CPQuery"; public static final String CP_QUERY_PARTICIPANT_EDIT_ACTION = "CPQueryParticipantEdit.do"; public static final String CP_QUERY_PARTICIPANT_ADD_ACTION = "CPQueryParticipantAdd.do"; public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "CPQuerySpecimenCollectionGroupAdd.do"; public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "CPQuerySpecimenCollectionGroupEdit.do"; public static final String CP_AND_PARTICIPANT_VIEW="cpAndParticipantView"; public static final String DATA_DETAILS_VIEW="dataDetailsView"; public static final String SHOW_CP_AND_PARTICIPANTS_ACTION="showCpAndParticipants.do"; public static final String PAGE_OF_CP_QUERY_RESULTS = "pageOfCpQueryResults"; public static final String CP_LIST = "cpList"; public static final String CP_ID_TITLE_MAP = "cpIDTitleMap"; public static final String REGISTERED_PARTICIPANT_LIST = "participantList"; public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery"; public static final String PAGE_OF_SCG_CP_QUERY = "pageOfSpecimenCollectionGroupCPQuery"; public static final String CP_SEARCH_PARTICIPANT_ID="cpSearchParticipantId"; public static final String CP_SEARCH_CP_ID="cpSearchCpId"; public static final String CP_TREE_VIEW = "cpTreeView"; public static final String CP_TREE_VIEW_ACTION = "showTree.do"; public static final String PAGE_OF_SPECIMEN_CP_QUERY = "pageOfNewSpecimenCPQuery"; public static final String CP_QUERY_SPECIMEN_ADD_ACTION = "CPQueryNewSpecimenAdd.do"; public static final String CP_QUERY_CREATE_SPECIMEN_ACTION = "CPQueryCreateSpecimen.do"; public static final String CP_QUERY_SPECIMEN_EDIT_ACTION = "CPQueryNewSpecimenEdit.do"; public static final String PAGE_OF_CREATE_SPECIMEN_CP_QUERY = "pageOfCreateSpecimenCPQuery"; public static final String PAGE_OF_ALIQUOT_CP_QUERY = "pageOfAliquotCPQuery"; public static final String PAGE_OF_CREATE_ALIQUOT_CP_QUERY = "pageOfCreateAliquotCPQuery"; public static final String PAGE_OF_ALIQUOT_SUMMARY_CP_QUERY = "pageOfAliquotSummaryCPQuery"; public static final String CP_QUERY_CREATE_ALIQUOT_ACTION = "CPQueryCreateAliquots.do"; public static final String CP_QUERY_ALIQUOT_SUMMARY_ACTION = "CPQueryAliquotSummary.do"; public static final String CP_QUERY_CREATE_SPECIMEN_ADD_ACTION = "CPQueryAddSpecimen.do"; public static final String PAGE_OF_DISTRIBUTION_CP_QUERY = "pageOfDistributionCPQuery"; public static final String CP_QUERY_DISTRIBUTION_EDIT_ACTION = "CPQueryDistributionEdit.do"; public static final String CP_QUERY_DISTRIBUTION_ADD_ACTION = "CPQueryDistributionAdd.do"; public static final String CP_QUERY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryDistributionReportSave.do"; public static final String CP_QUERY_ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryArrayDistributionReportSave.do"; public static final String CP_QUERY_CONFIGURE_DISTRIBUTION_ACTION = "CPQueryConfigureDistribution.do"; public static final String CP_QUERY_DISTRIBUTION_REPORT_ACTION = "CPQueryDistributionReport.do"; public static final String PAGE_OF_LIST_SPECIMEN_EVENT_PARAMETERS_CP_QUERY = "pageOfListSpecimenEventParametersCPQuery"; public static final String PAGE_OF_LIST_SPECIMEN_EVENT_PARAMETERS = "pageOfListSpecimenEventParameters"; public static final String PAGE_OF_COLLECTION_PROTOCOL_REGISTRATION_CP_QUERY = "pageOfCollectionProtocolRegistrationCPQuery"; public static final String PAGE_OF_MULTIPLE_SPECIMEN_CP_QUERY = "pageOfMultipleSpecimenCPQuery"; public static final String CP_QUERY_NEW_MULTIPLE_SPECIMEN_ACTION = "CPQueryNewMultipleSpecimenAction.do"; public static final String CP_QUERY_MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="CPQueryMultipleSpecimenStorageLocationAdd.do"; public static final String CP_QUERY_PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "CPQueryformSubmitted"; public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_ADD_ACTION = "CPQueryCollectionProtocolRegistrationAdd.do"; public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CPQueryCollectionProtocolRegistrationEdit.do"; public static final String CP_QUERY_PARTICIPANT_LOOKUP_ACTION= "CPQueryParticipantLookup.do"; public static final String CP_QUERY_BIO_SPECIMEN = "/QueryManageBioSpecimen.do"; //Mandar : 15-Jan-07 public static final String WITHDRAW_RESPONSE_NOACTION= "No Action"; public static final String WITHDRAW_RESPONSE_DISCARD= "Discard"; public static final String WITHDRAW_RESPONSE_RETURN= "Return"; public static final String WITHDRAW_RESPONSE_RESET= "Reset"; public static final String WITHDRAW_RESPONSE_REASON= "Specimen consents withdrawn"; public static final String SEARCH_CATEGORY_LIST_SELECT_TAG_NAME="selectCategoryList"; public static final String SEARCH_CATEGORY_LIST_FUNCTION_NAME="getSelectedEntities"; public static final String EDIT_CONDN = "Edit"; public static final String SPLITTER_STATUS_REQ_PARAM = "SPLITTER_STATUS"; //mulltiple specimen Applet constants public static final int VALIDATE_TEXT =1; public static final int VALIDATE_COMBO =2; public static final int VALIDATE_DATE =3; /** * Constants required for maintaining toolTipText for event button on multiple specimen page */ public static final String TOOLTIP_TEXT="TOOLTIPTEXT"; public static final String MULTIPLE_SPECIMEN_TOOLTIP_MAP_KEY="multipleSpecimenTooltipMapKey"; public static final String DEFAULT_TOOLTIP_TEXT="DEFAULTTOOLTIPTEXT"; /** * Patch ID: Bug#3184_15 (for Multiple Specimen) * Description: The following constants are used as key in the Map */ public static final String KEY_SPECIMEN_CLASS = "SpecimenClass"; public static final String KEY_SPECIMEN_TYPE = "SpecimenType"; public static final String KEY_TISSUE_SITE = "TissueSite"; public static final String KEY_PATHOLOGICAL_STATUS = "PathologicalStatus"; public static final String KEY_SPECIMEN_REQUIREMENT_PREFIX = "SpecimenRequirement_"; public static final String KEY_RESTRICTED_VALUES = "RestictedValues"; public static final String KEY_QUANTITY = "Quantity"; // The following constants are used for multiple specimens applet classes public static final String NUMBER_OF_SPECIMEN_REQUIREMENTS = "numberOfSpecimenRequirements"; public static final String RESTRICT_SCG_CHECKBOX = "restrictSCGCheckbox"; public static final String ON_COLL_OR_CLASSCHANGE = "onCollOrClassChange"; public static final String NUMBER_OF_SPECIMENS = "numberOfSpecimens"; public static final String CHANGE_ON = "changeOn"; // Patch ID: Bug#4180_3 public static final String EVENT_NAME = "eventName"; public static final String USER_NAME = "userName"; public static final String EVENT_DATE = "eventDate"; public static final String PAGE_OF = "pageOf"; /** * Patch ID: for Future SCG_15 * Description: The following constants are used as id for future scg in tree */ public static final String FUTURE_SCG = "future"; // Patch ID: SimpleSearchEdit_5 // AliasName constants, used in Edit in Simple Search feature. public static final String ALIAS_COLLECTION_PROTOCOL = "CollectionProtocol"; public static final String ALIAS_BIOHAZARD = "Biohazard"; public static final String ALIAS_CANCER_RESEARCH_GROUP = "CancerResearchGroup"; public static final String ALIAS_COLLECTION_PROTOCOL_REG = "CollectionProtReg"; public static final String ALIAS_DEPARTMENT = "Department"; public static final String ALIAS_DISTRIBUTION = "Distribution"; public static final String ALIAS_DISTRIBUTION_PROTOCOL = "DistributionProtocol"; public static final String ALIAS_DISTRIBUTION_ARRAY = "Distribution_array"; public static final String ALIAS_INSTITUTE = "Institution"; public static final String ALIAS_PARTICIPANT = "Participant"; public static final String ALIAS_SITE = "Site"; public static final String ALIAS_SPECIMEN = "Specimen"; public static final String ALIAS_SPECIMEN_ARRAY = "SpecimenArray"; public static final String ALIAS_SPECIMEN_ARRAY_TYPE = "SpecimenArrayType"; public static final String ALIAS_SPECIMEN_COLLECTION_GROUP = "SpecimenCollectionGroup"; public static final String ALIAS_STORAGE_CONTAINER = "StorageContainer"; public static final String ALIAS_STORAGE_TYPE= "StorageType"; public static final String ALIAS_USER= "User"; public static final String PAGE_OF_BIOHAZARD = "pageOfBioHazard"; public static final String PAGE_OF_CANCER_RESEARCH_GROUP = "pageOfCancerResearchGroup"; public static final String PAGE_OF_COLLECTION_PROTOCOL = "pageOfCollectionProtocol"; public static final String PAGE_OF_COLLECTION_PROTOCOL_REG = "pageOfCollectionProtocolRegistration"; public static final String PAGE_OF_DEPARTMENT = "pageOfDepartment"; public static final String PAGE_OF_DISTRIBUTION = "pageOfDistribution"; public static final String PAGE_OF_DISTRIBUTION_PROTOCOL = "pageOfDistributionProtocol"; public static final String PAGE_OF_DISTRIBUTION_ARRAY = "pageOfArrayDistribution"; public static final String PAGE_OF_INSTITUTE = "pageOfInstitution"; public static final String PAGE_OF_PARTICIPANT = "pageOfParticipant"; public static final String PAGE_OF_SITE = "pageOfSite"; public static final String PAGE_OF_SPECIMEN = "pageOfSpecimen"; public static final String PAGE_OF_SPECIMEN_ARRAY = "pageOfSpecimenArray"; public static final String PAGE_OF_SPECIMEN_ARRAY_TYPE = "pageOfSpecimenArrayType"; public static final String PAGE_OF_SPECIMEN_COLLECTION_GROUP = "pageOfSpecimenCollectionGroup"; public static final String PAGE_OF_STORAGE_CONTAINER = "pageOfStorageContainer"; public static final String PAGE_OF_STORAGE_TYPE = "pageOfStorageType"; public static final String PAGE_OF_USER = "pageOfUserAdmin"; //Patch ID: Bug#4227_3 public static final String SUBMIT_AND_ADD_MULTIPLE = "submitAndAddMultiple"; //constants for Storage container map radio button identification Patch id: 4283_3 public static final int RADIO_BUTTON_VIRTUALLY_LOCATED=1; public static final int RADIO_BUTTON_FOR_MAP=3; // constant for putting blank screen in the framed pages public static final String BLANK_SCREEN_ACTION="blankScreenAction.do"; public static final String COLUMN_NAME_SPECIMEN_ID = "specimen.id"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER="ParticipantMedicalIdentifier:"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER_SITE_ID="_Site_id"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER_MEDICAL_NUMBER="_medicalRecordNumber"; public static final String PARTICIPANT_MEDICAL_IDENTIFIER_ID="_id"; public static final String COLUMN_NAME_SPECIEMEN_REQUIREMENT_COLLECTION="elements(specimenRequirementCollection)"; public static final String COLUMN_NAME_PARTICIPANT="participant"; public static final String ADDNEW_LINK="AddNew"; public static final String COLUMN_NAME_STORAGE_CONTAINER = "storageContainer"; public static final String COLUMN_NAME_SCG_CPR_CP_ID = "specimenCollectionGroup.collectionProtocolRegistration.collectionProtocol.id"; public static final String COLUMN_NAME_CPR_CP_ID = "collectionProtocolRegistration.collectionProtocol.id"; public static final String EQUALS = "="; public static final String COLUMN_NAME_SCG_NAME = "specimenCollectionGroup.name"; public static final String COLUMN_NAME_SPECIMEN = "specimen"; public static final String COLUMN_NAME_SCG = "specimenCollectionGroup"; public static final String COLUMN_NAME_CHILDREN = "elements(children)"; public static final String COLUMN_NAME_SCG_ID="specimenCollectionGroup.id"; public static final String COLUMN_NAME_PART_MEDICAL_ID_COLL="elements(participantMedicalIdentifierCollection)"; public static final String COLUMN_NAME_PART_RACE_COLL="elements(raceCollection)"; public static final String COLUMN_NAME_CPR_COLL="elements(collectionProtocolRegistrationCollection)"; public static final String COLUMN_NAME_SCG_COLL="elements(specimenCollectionGroupCollection)"; public static final String COLUMN_NAME_COLL_PROT_EVENT_COLL="elements(collectionProtocolEventCollection)"; public static final String COLUMN_NAME_CONCEPT_REF_COLL="elements(conceptReferentCollection)"; public static final String COLUMN_NAME_DEID_REPORT="deIdentifiedSurgicalPathologyReport"; public static final String COLUMN_NAME_REPORT_SOURCE="reportSource"; public static final String COLUMN_NAME_TEXT_CONTENT="textContent"; public static final String COLUMN_NAME_TITLE="title"; public static final String COLUMN_NAME_PARTICIPANT_ID = "participant.id"; public static final String COLUMN_NAME_REPORT_SECTION_COLL="elements(reportSectionCollection)"; public static final String COLUMN_NAME_SCG_SITE="specimenCollectionSite"; public static final String COLUMN_NAME_STATUS="status"; public static final String COLUMN_NAME_CPR="collectionProtocolRegistration"; public static final String COLUMN_NAME_COLL_PROT_EVENT="collectionProtocolEvent"; //Bug 2833. Field for the length of CP Title public static final int COLLECTION_PROTOCOL_TITLE_LENGTH=30; //Bug ID 4794: Field for advance time to warn a user about session expiry public static final String SESSION_EXPIRY_WARNING_ADVANCE_TIME = "session.expiry.warning.advanceTime"; // Constants required in RequestDetailsPage public static final String SUBMIT_REQUEST_DETAILS_ACTION="SubmitRequestDetails.do"; public static final String REQUEST_HEADER_OBJECT = "requestHeaderObject"; public static final String SITE_LIST_OBJECT = "siteList"; public static final String REQUEST_DETAILS_PAGE = "RequestDetails.do"; public static final String ARRAYREQUEST_DETAILS_PAGE = "ArrayRequests.do"; public static final String ARRAY_REQUESTS_LIST = "arrayRequestsList"; public static final String EXISISTINGARRAY_REQUESTS_LIST = "existingArrayRequestDetailsList"; public static final String DEFINEDARRAY_REQUESTS_LIST = "DefinedRequestDetailsMapList"; public static final String ITEM_STATUS_LIST="itemsStatusList"; public static final String ITEM_STATUS_LIST_WO_DISTRIBUTE="itemsStatusListWithoutDistribute"; public static final String ITEM_STATUS_LIST_FOR_ITEMS_IN_ARRAY="itemsStatusListForItemsInArray"; public static final String REQUEST_FOR_LIST="requestForList"; // Constants for Order Request Status. public static final String ORDER_REQUEST_STATUS_NEW = "New"; public static final String ORDER_REQUEST_STATUS_PENDING_PROTOCOL_REVIEW = "Pending - Protocol Review"; public static final String ORDER_REQUEST_STATUS_PENDING_SPECIMEN_PREPARATION = "Pending - Specimen Preparation"; public static final String ORDER_REQUEST_STATUS_PENDING_FOR_DISTRIBUTION = "Pending - For Distribution"; public static final String ORDER_REQUEST_STATUS_REJECTED_INAPPROPRIATE_REQUEST = "Rejected - Inappropriate Request"; public static final String ORDER_REQUEST_STATUS_REJECTED_SPECIMEN_UNAVAILABLE = "Rejected - Specimen Unavailable"; public static final String ORDER_REQUEST_STATUS_REJECTED_UNABLE_TO_CREATE = "Rejected - Unable to Create"; public static final String ORDER_REQUEST_STATUS_DISTRIBUTED = "Distributed"; public static final String ORDER_REQUEST_STATUS_READY_FOR_ARRAY_PREPARATION = "Ready For Array Preparation"; // Used for tree display in RequestDetails page public static final String TREE_DATA_LIST = "treeDataList"; //Constants for Order Status public static final String ORDER_STATUS_NEW = "New"; public static final String ORDER_STATUS_PENDING = "Pending"; public static final String ORDER_STATUS_REJECTED = "Rejected"; public static final String ORDER_STATUS_COMPLETED = "Completed"; // Ordering System Status public static final String CDE_NAME_REQUEST_STATUS="Request Status"; public static final String CDE_NAME_REQUESTED_ITEMS_STATUS="Requested Items Status"; public static final String REQUEST_LIST="requestStatusList"; public static final String REQUESTED_ITEMS_STATUS_LIST="requestedItemsStatusList"; public static final String ARRAY_STATUS_LIST="arrayStatusList"; public static final String REQUEST_OBJECT="requestObjectList"; public static final String REQUEST_DETAILS_LIST="requestDetailsList"; public static final String ARRAY_REQUESTS_BEAN_LIST="arrayRequestsBeanList"; public static final String SPECIMEN_ORDER_FORM_TYPE = "specimen"; public static final String ARRAY_ORDER_FORM_TYPE = "specimenArray"; public static final String PATHOLOGYCASE_ORDER_FORM_TYPE="pathologyCase"; public static final String REQUESTED_BIOSPECIMENS="RequestedBioSpecimens"; //Constants required in Ordering System. public static final String ACTION_ORDER_LIST = "OrderExistingSpecimen.do"; public static final String SPECIMEN_TREE_SPECIMEN_ID = "specimenId"; public static final String SPECIMEN_TREE_SPECCOLLGRP_ID = "specimenCollGrpId"; public static final String ACTION_REMOVE_ORDER_ITEM = "AddToOrderListSpecimen.do?remove=yes"; public static final String ACTION_REMOVE_ORDER_ITEM_ARRAY = "AddToOrderListArray.do?remove=yes"; public static final String ACTION_REMOVE_ORDER_ITEM_PATHOLOGYCASE = "AddToOrderListPathologyCase.do?remove=yes"; public static final String DEFINEARRAY_REQUESTMAP_LIST = "definedArrayRequestMapList"; public static final String CREATE_DEFINED_ARRAY = "CreateDefinedArray.do"; public static final String ACTION_SAVE_ORDER_ITEM = "SaveOrderItems.do"; public static final String ORDERTO_LIST_ARRAY = "orderToListArrayList"; public static final String ACTION_SAVE_ORDER_ARRAY_ITEM = "SaveOrderArrayItems.do"; public static final String ACTION_SAVE_ORDER_PATHOLOGY_ITEM="SaveOrderPathologyItems.do"; public static final String ACTION_ADD_ORDER_SPECIMEN_ITEM="AddToOrderListSpecimen.do"; public static final String ACTION_ADD_ORDER_ARRAY_ITEM="AddToOrderListArray.do"; public static final String ACTION_ADD_ORDER_PATHOLOGY_ITEM="AddToOrderListPathologyCase.do"; public static final String ACTION_DEFINE_ARRAY="DefineArraySubmit.do"; public static final String ACTION_ORDER_SPECIMEN="OrderExistingSpecimen.do"; public static final String ACTION_ORDER_BIOSPECIMENARRAY="OrderBiospecimenArray.do"; public static final String ACTION_ORDER_PATHOLOGYCASE="OrderPathologyCase.do"; //Specimen Label generation realted constants public static final String PARENT_SPECIMEN_ID_KEY="parentSpecimenID"; public static final String PARENT_SPECIMEN_LABEL_KEY="parentSpecimenLabel"; public static final String SCG_NAME_KEY="SCGName"; //ordering system public static final String TAB_INDEX_ID="tabIndexId"; public static final String FORWARD_TO_HASHMAP="forwardToHashMap"; public static final String SELECTED_COLLECTION_PROTOCOL_ID = "0"; public static final String LIST_OF_SPECIMEN_COLLECTION_GROUP = "specimenCollectionGroupResponseList"; public static final String PARTICIPANT_PROTOCOL_ID="participantProtocolId"; // caTIES public static final String REPORT_QUEUE_LIST = "ReportQueueList"; public static final String BUTTON_NAME = "button"; public static final String CREATE_PARTICIPANT_BUTTON = "createParticipant"; public static final String ASSOCIATE_PARTICIPANT_BUTTON = "associateParticipant"; public static final String REPORT_PARTICIPANT_OBJECT = "reportParticipantObject"; public static final String REPORT_ID = "reportQueueId"; public static final String PARTICIPANT_ID_TO_ASSOCIATE = "participantIdToAssociate"; public static final String SCG_ID_TO_ASSOCIATE = "scgIdToAssociate"; public static final String CONCEPT_REFERENT_CLASSIFICATION_LIST = "conceptRefernetClassificationList"; public static final String CONCEPT_LIST = "conceptList"; public static final String[] CATEGORY_HIGHLIGHTING_COLOURS = {"#ff6d5f","#db9fe5","#2dcc00","#69bbf7","#f8e754"}; public static final String CONCEPT_BEAN_LIST = "conceptBeanList"; //Admin View public static final String IDENTIFIER_NO=" public static final String REQUEST_DATE="Request Date"; public static final String USER_NAME_ADMIN_VIEW="User Name"; public static final String SCG_NAME="Specimen Collection Group"; public static final String ACCESSION_NO="Accession Number"; public static final String REVIEW_SPR="reviewSPR"; public static final String QUARANTINE_SPR="quarantineSPR"; public static final String SITE="Site"; public static final String REQUEST_FOR="requestFor"; public static final String REPORT_ACTION="reportAction"; public static final String REPORT_STATUS_LIST="reportStatusList"; public static final String COLUMN_LIST="columnList"; //Surgical Pathology Report UI constants public static final String VIEW_SPR_ACTION="ViewSurgicalPathologyReport.do"; public static final String SPR_EVENT_PARAM_ACTION="SurgicalPathologyReportEventParam.do"; public static final String VIEW_SURGICAL_PATHOLOGY_REPORT="viewSPR"; public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP="pageOfSpecimenCollectionGroup"; public static final String PAGEOF_PARTICIPANT="pageOfParticipant"; public static final String PAGEOF_NEW_SPECIMEN="pageOfNewSpecimen"; public static final String REVIEW="REVIEW"; public static final String QUARANTINE="QUARANTINE"; public static final String COMMENT_STATUS_RENDING="PENDING"; public static final String COMMENT_STATUS_REVIEWED="REVIEWED"; public static final String COMMENT_STATUS_REPLIED="REPLIED"; public static final String COMMENT_STATUS_NOT_REVIEWED="NOT_REVIEWED"; public static final String COMMENT_STATUS_QUARANTINED="QUARANTINED"; public static final String COMMENT_STATUS_NOT_QUARANTINED="DEQUARANTINED"; public static final String ROLE_ADMINISTRATOR="Administrator"; public static final String REPORT_LIST="reportIdList"; public static final String QUARANTINE_REQUEST="QUARANTINEREQUEST"; public static final String IDENTIFIED_REPORT_NOT_FOUND_MSG="Indentified Report Not Found!"; public static final String DEID_REPORT_NOT_FOUND_MSG="De-Indentified Report Not Found!"; // Local extensions constants public static final String LOCAL_EXT="localExt"; public static final String LINK="link"; public static final String LOAD_INTEGRATION_PAGE="loadIntegrationPage"; public static final String DEFINE_ENTITY = "defineEntity"; public static final String SELECTED_ENTITY_ID="selectedStaticEntityId"; public static final String CONTAINER_NAME="containerName"; public static final String STATIC_ENTITY_NAME = "staticEntityName"; public static final String SPREADSHEET_DATA_GROUP="spreadsheetDataGroup"; public static final String SPREADSHEET_DATA_ENTITY="spreadsheetDataEntity"; public static final String SPREADSHEET_DATA_RECORD="spreadsheetDataRecord"; //clinportal constants public static final int CLINICALSTUDY_FORM_ID = 65; public static final int CLINICAL_STUDY_REGISTRATION_FORM_ID=66; //Ordering constants public static final String ARRAY_NAME = "array"; //Query Shopping cart constants //public static final String DUPLICATE_OBJECT_IN_CART = "duplicate object added in cart"; public static final String SHOPPING_CART_FILE_NAME = "ShoppingCart.csv"; public static final String ADD_TO_CART = ""; public static final String DUPLICATE_OBJECT = "duplicateObject"; public static final String DIFFERENT_VIEW_IN_CART = "differentCartView"; public static final String COLLECTION_PROTOCOL_EVENT_ID = "Event_Id"; }
package render; import java.util.ArrayList; import java.util.List; import entities.RenderObject; public class ZBuffer { public List<RenderObject> rendering_objects; public ZBuffer() { this.rendering_objects = new ArrayList<RenderObject>(); } public void orderObjects(List<RenderObject> toBeOrdered) { this.rendering_objects.clear(); // The ordering and Z buffer determination goes here: RenderObject previousY = null; for (RenderObject i : toBeOrdered) { // Don't know how to use Comparators, so I'll do it the traditional way. if (previousY == null) { this.rendering_objects.add(i); continue; } if (i.position.y < previousY.position.y) this.rendering_objects.add(this.rendering_objects.indexOf(previousY), i); else this.rendering_objects.add(i); previousY = i; } } }
package com.codeborne.selenide; import java.util.logging.Logger; import static com.codeborne.selenide.Configuration.AssertionMode.STRICT; import static com.codeborne.selenide.Configuration.FileDownloadMode.HTTPGET; import static com.codeborne.selenide.Configuration.SelectorMode.CSS; import static com.codeborne.selenide.WebDriverRunner.FIREFOX; public class Configuration { private static final Logger LOG = Logger.getLogger(Configuration.class.getName()); public static String baseUrl = System.getProperty("selenide.baseUrl", "http://localhost:8080"); /** * Timeout in milliseconds for a collection to get completely loaded * Conditions will be checked at this point at latest, even if they are still loading * Can be configured either programmatically or by system property "-Dselenide.collectionsTimeout=10000" * Default value: 6000 (milliseconds) */ public static long collectionsTimeout = Long.parseLong(System.getProperty("selenide.collectionsTimeout", "6000")); /** * Timeout in milliseconds to fail the test, if conditions still not met * Can be configured either programmatically or by system property "-Dselenide.timeout=10000" * Default value: 4000 (milliseconds) */ public static long timeout = Long.parseLong(System.getProperty("selenide.timeout", "4000")); /** * Interval in milliseconds, when checking if a single element is appeared * Can be configured either programmatically or by system property "-Dselenide.pollingInterval=50" * Default value: 100 (milliseconds) */ public static long pollingInterval = Long.parseLong(System.getProperty("selenide.pollingInterval", "100")); /** * Interval in milliseconds, when checking if a new collection elements appeared * Can be configured either programmatically or by system property "-Dselenide.collectionsPollingInterval=150" * Default value: 200 (milliseconds) */ public static long collectionsPollingInterval = Long.parseLong( System.getProperty("selenide.collectionsPollingInterval", "200")); /** * If holdBrowserOpen is true, browser window stays open after running tests. It may be useful for debugging. * Can be configured either programmatically or by system property "-Dselenide.holdBrowserOpen=true". * <p/> * Default value: false. */ public static boolean holdBrowserOpen = Boolean.getBoolean("selenide.holdBrowserOpen"); /** * Should Selenide re-spawn browser if it's disappeared (hangs, broken, unexpectedly closed). * <p> * Can be configured either programmatically or by system property "-Dselenide.reopenBrowserOnFail=false". * <p> * Default value: true * Set this property to false if you want to disable automatic re-spawning the browser. */ public static boolean reopenBrowserOnFail = Boolean.parseBoolean( System.getProperty("selenide.reopenBrowserOnFail", "true")); /** * Timeout (in milliseconds) for opening (creating) a browser (webdriver). * <p/> * Can be configured either programmatically or by system property "-Dselenide.openBrowserTimeout=10000" * Default value: 15000 (milliseconds) */ public static long openBrowserTimeoutMs = Long.parseLong(System.getProperty("selenide.openBrowserTimeout", "15000")); /** * Timeout (in milliseconds) for closing/killing browser. * <p/> * Sometimes we have problems with calling driver.close() or driver.quit() method, and test always is suspended too long. * <p/> * Can be configured either programmatically or by system property "-Dselenide.closeBrowserTimeout=10000" * Default value: 5000 (milliseconds) */ public static long closeBrowserTimeoutMs = Long.parseLong(System.getProperty("selenide.closeBrowserTimeout", "5000")); /** * Which browser to use. * Can be configured either programmatically or by system property "-Dselenide.browser=ie" or "-Dbrowser=ie". * Supported values: "chrome", "firefox", "ie", "htmlunit", "phantomjs", "opera", "marionette" * <p/> * Default value: "firefox" */ public static String browser = System.getProperty("selenide.browser", System.getProperty("browser", FIREFOX)); /** * Which browser version to use (for Internet Explorer). * Can be configured either programmatically or by system property "-Dselenide.browserVersion=8" or "-Dbrowser.version=8". * <p/> * Default value: none */ public static String browserVersion = System.getProperty("selenide.browserVersion", System.getProperty("selenide.browser.version", System.getProperty("browser.version"))); public static String remote = System.getProperty("remote"); /** * The browser window size. * Can be configured either programmatically or by system property "-Dselenide.browserSize=1024x768". * * Default value: none (browser size will not be set explicitly) */ public static String browserSize = System.getProperty("selenide.browserSize", System.getProperty("selenide.browser-size")); /** * The browser window is maximized when started. * Can be configured either programmatically or by system property "-Dselenide.startMaximized=true". * <p> * Default value: true */ public static boolean startMaximized = Boolean.parseBoolean(System.getProperty("selenide.startMaximized", System.getProperty("selenide.start-maximized", "true"))); /** * @deprecated this options allowed only a single switch. * Please use more generic -Dchromeoptions.args=<comma-separated list of switches> instead * * Value of "chrome.switches" parameter (in case of using Chrome driver). * Can be configured either programmatically or by system property, * i.e. "-Dselenide.chrome.switches=--disable-popup-blocking". * * Default value: none */ @Deprecated public static String chromeSwitches = System.getProperty("selenide.chrome.switches", System.getProperty("chrome.switches")); public static String pageLoadStrategy = System.getProperty("selenide.pageLoadStrategy", System.getProperty("selenide.page-load-strategy", "normal")); /** * ATTENTION! Automatic WebDriver waiting after click isn't working in case of using this feature. * Use clicking via JavaScript instead common element clicking. * This solution may be helpful for testing in Internet Explorer. * Can be configured either programmatically or by system property "-Dselenide.clickViaJs=true". * Default value: false */ public static boolean clickViaJs = Boolean.parseBoolean(System.getProperty("selenide.clickViaJs", System.getProperty("selenide.click-via-js", "false"))); /** * Defines if Selenide tries to capture JS errors * Can be configured either programmatically or by system property "-Dselenide.captureJavascriptErrors=false". * * Default value: true */ public static boolean captureJavascriptErrors = Boolean.parseBoolean(System.getProperty("selenide.captureJavascriptErrors", "true")); /** * Defines if Selenide takes screenshots on failing tests. * Can be configured either programmatically or by system property "-Dselenide.screenshots=false". * * Default value: true */ public static boolean screenshots = Boolean.parseBoolean(System.getProperty("selenide.screenshots", "true")); /** * Defines if Selenide saves page source on failing tests. * Can be configured either programmatically or by system property "-Dselenide.savePageSource=false". * Default value: true */ public static boolean savePageSource = Boolean.parseBoolean(System.getProperty("selenide.savePageSource", "true")); /** * Folder to store screenshots to. * Can be configured either programmatically or by system property "-Dselenide.reportsFolder=test-result/reports". * * Default value: "build/reports/tests" (this is default for Gradle projects) */ public static String reportsFolder = System.getProperty("selenide.reportsFolder", System.getProperty("selenide.reports", "build/reports/tests")); public static String reportsUrl = getReportsUrl(); static String getReportsUrl() { String reportsUrl = System.getProperty("selenide.reportsUrl"); if (isEmpty(reportsUrl)) { reportsUrl = getJenkinsReportsUrl(); if (isEmpty(reportsUrl)) { LOG.config("Variable selenide.reportsUrl not found"); } } else { LOG.config("Using variable selenide.reportsUrl=" + reportsUrl); } return reportsUrl; } private static boolean isEmpty(String s) { return s == null || s.trim().isEmpty(); } private static String getJenkinsReportsUrl() { String build_url = System.getProperty("BUILD_URL"); if (!isEmpty(build_url)) { LOG.config("Using Jenkins BUILD_URL: " + build_url); return build_url + "artifact/"; } else { LOG.config("No BUILD_URL variable found. It's not Jenkins."); return null; } } /** * Mock "alert" and "confirm" javascript dialogs. * Can be configured either programmatically or by system property "-Dselenide.dismissModalDialogs=true". * * Default value: false * (true for headless browsers like HtmlUnit and PhantomJS because they do not support alert/confirm anyway) */ public static boolean dismissModalDialogs = Boolean.parseBoolean(System.getProperty("selenide.dismissModalDialogs", "false")); public static boolean fastSetValue = Boolean.parseBoolean(System.getProperty("selenide.fastSetValue", "false")); public static boolean versatileSetValue = Boolean.parseBoolean(System.getProperty("selenide.versatileSetValue", "false")); /** * Choose how Selenide should retrieve web elements: using default CSS or Sizzle (CSS3) */ public static SelectorMode selectorMode = CSS; public enum SelectorMode { /** * Default Selenium behavior */ CSS, /** * Use Sizzle for CSS selectors. * It allows powerful CSS3 selectors - ":input", ":not", ":nth", ":first", ":last", ":contains('text')" * * For other selectors (XPath, ID etc.) uses default Selenium mechanism. */ Sizzle } /** * Assertion modes available */ public enum AssertionMode { /** * Default mode - tests are failing immediately */ STRICT, /** * Test are failing only at the end of the methods. */ SOFT } /** * Assertion mode - STRICT or SOFT Asserts * Default value: STRICT * * @see AssertionMode */ public static AssertionMode assertionMode = STRICT; public enum FileDownloadMode { /** * Download files via direct http request. * Works only for <a href></a> elements. * Sends GET request to "href" with all cookies from current browser session. */ HTTPGET, /** * Download files via selenide embedded proxy server. * Works for any elements (e.g. form submission). * Doesn't work if you are using custom webdriver without selenide proxy server. */ PROXY } /** * Defines if files are downloaded via direct HTTP or vie selenide emebedded proxy server * Can be configured either programmatically or by system property "-Dselenide.fileDownload=PROXY" * Default: HTTPGET */ public static FileDownloadMode fileDownload = FileDownloadMode.valueOf( System.getProperty("selenide.fileDownload", HTTPGET.name())); public static boolean driverManagerEnabled = Boolean.parseBoolean(System.getProperty("selenide.driverManagerEnabled", "true")); }
package net.somethingdreadful.MAL; import android.content.Context; import android.util.Log; import com.crashlytics.android.Crashlytics; import net.somethingdreadful.MAL.account.AccountService; import net.somethingdreadful.MAL.api.ALApi; import net.somethingdreadful.MAL.api.ALModels.ForumAL; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Anime; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.BrowseList; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Manga; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.Reviews; import net.somethingdreadful.MAL.api.BaseModels.AnimeManga.UserList; import net.somethingdreadful.MAL.api.BaseModels.Forum; import net.somethingdreadful.MAL.api.BaseModels.History; import net.somethingdreadful.MAL.api.BaseModels.Profile; import net.somethingdreadful.MAL.api.MALApi; import net.somethingdreadful.MAL.database.DatabaseManager; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; public class MALManager { private MALApi malApi; private ALApi alApi; private final DatabaseManager dbMan; public MALManager(Context context) { if (AccountService.isMAL()) malApi = new MALApi(); else alApi = new ALApi(); dbMan = new DatabaseManager(context); } public static String listSortFromInt(int i, MALApi.ListType type) { switch (i) { case 0: return ""; case 1: return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_WATCHING : Manga.STATUS_READING; case 2: return Anime.STATUS_COMPLETED; case 3: return Anime.STATUS_ONHOLD; case 4: return Anime.STATUS_DROPPED; case 5: return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_PLANTOWATCH : Manga.STATUS_PLANTOREAD; case 6: return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_REWATCHING : Manga.STATUS_REREADING; default: return type.equals(MALApi.ListType.ANIME) ? Anime.STATUS_WATCHING : Manga.STATUS_READING; } } public Anime getAnime(int id) { Crashlytics.log(Log.INFO, "MALX", "MALManager.getAnime() : Loading " + id); return dbMan.getAnime(id); } public Manga getManga(int id) { Crashlytics.log(Log.INFO, "MALX", "MALManager.getManga() : Loading " + id); return dbMan.getManga(id); } public void downloadAnimeList(String username) { Crashlytics.log(Log.INFO, "MALX", "MALManager.downloadAnimeList() : Downloading " + username); UserList animeList = AccountService.isMAL() ? malApi.getAnimeList() : alApi.getAnimeList(username); if (animeList != null) { dbMan.saveAnimeList(animeList.getAnimeList()); dbMan.cleanupAnimeTable(); } } public void downloadMangaList(String username) { Crashlytics.log(Log.INFO, "MALX", "MALManager.downloadMangaList() : Downloading " + username); UserList mangaList = AccountService.isMAL() ? malApi.getMangaList() : alApi.getMangaList(username); if (mangaList != null) { dbMan.saveMangaList(mangaList.getMangaList()); dbMan.cleanupMangaTable(); } } public ArrayList<Anime> getAnimeListFromDB(String ListType, int sortType, String inverse) { return dbMan.getAnimeList(ListType, sortType, inverse.equals("false") ? 1 : 2); } public ArrayList<Manga> getMangaListFromDB(String ListType, int sortType, String inverse) { return dbMan.getMangaList(ListType, sortType, inverse.equals("false") ? 1 : 2); } public Manga updateWithDetails(int id, Manga manga) { Crashlytics.log(Log.INFO, "MALX", "MALManager.updateWithDetails() : Downloading manga " + id); Manga manga_api = AccountService.isMAL() ? malApi.getManga(id, 1) : alApi.getManga(id); if (manga_api != null) { dbMan.saveManga(manga_api); return AccountService.isMAL() ? manga_api : dbMan.getManga(id); } return manga; } public Anime updateWithDetails(int id, Anime anime) { Crashlytics.log(Log.INFO, "MALX", "MALManager.updateWithDetails() : Downloading anime " + id); Anime anime_api = AccountService.isMAL() ? malApi.getAnime(id, 1) : alApi.getAnime(id); if (anime_api != null) { dbMan.saveAnime(anime_api); return AccountService.isMAL() ? anime_api : dbMan.getAnime(id); } return anime; } public ArrayList<Profile> downloadAndStoreFriendList(String user) { ArrayList<Profile> result = new ArrayList<>(); try { Crashlytics.log(Log.DEBUG, "MALX", "MALManager.downloadAndStoreFriendList(): Downloading friendlist of " + user); result = AccountService.isMAL() ? malApi.getFriends(user) : alApi.getFollowers(user); if (result != null && result.size() > 0 && AccountService.getUsername().equals(user)) dbMan.saveFriendList(result); } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "MALManager.downloadAndStoreFriendList(): " + e.getMessage()); Crashlytics.logException(e); } return sortFriendlist(result); } private ArrayList<Profile> sortFriendlist(ArrayList<Profile> result) { //sort friendlist Collections.sort(result != null ? result : new ArrayList<Profile>(), new Comparator<Profile>() { @Override public int compare(Profile profile1, Profile profile2) { return profile1.getUsername().toLowerCase().compareTo(profile2.getUsername().toLowerCase()); } }); return result; } public ArrayList<Profile> getFriendListFromDB() { return dbMan.getFriendList(); } public Profile getProfile(String name) { Profile profile = new Profile(); try { Crashlytics.log(Log.DEBUG, "MALX", "MALManager.getProfile(): Downloading profile of " + name); profile = AccountService.isMAL() ? malApi.getProfile(name) : alApi.getProfile(name); if (profile != null) { profile.setUsername(name); if (name.equalsIgnoreCase(AccountService.getUsername())) dbMan.saveProfile(profile); } } catch (Exception e) { Crashlytics.log(Log.ERROR, "MALX", "MALManager.getProfile(): " + e.getMessage()); Crashlytics.logException(e); } return profile; } public Profile getProfileFromDB() { return dbMan.getProfile(); } public void saveAnimeToDatabase(Anime anime) { dbMan.saveAnime(anime); } public void saveMangaToDatabase(Manga manga) { dbMan.saveManga(manga); } public void cleanDirtyAnimeRecords() { ArrayList<Anime> dirtyAnimes = dbMan.getDirtyAnimeList(); if (dirtyAnimes != null) { Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyAnimeRecords(): Got " + dirtyAnimes.size() + " dirty anime records. Cleaning.."); for (Anime anime : dirtyAnimes) { if (writeAnimeDetails(anime)) { anime.clearDirty(); saveAnimeToDatabase(anime); } else if (anime != null) { Crashlytics.log(Log.ERROR, "MALX", "MALManager.cleanDirtyAnimeRecords(): Failed to update " + anime.getId() + "."); } } Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyAnimeRecords(): Cleaned dirty anime records."); } } public void cleanDirtyMangaRecords() { ArrayList<Manga> dirtyMangas = dbMan.getDirtyMangaList(); if (dirtyMangas != null) { Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyMangaRecords(): Got " + dirtyMangas.size() + " dirty manga records. Cleaning.."); for (Manga manga : dirtyMangas) { if (writeMangaDetails(manga)) { manga.clearDirty(); saveMangaToDatabase(manga); } else if (manga != null) { Crashlytics.log(Log.ERROR, "MALX", "MALManager.cleanDirtyMangaRecords(): Failed to update " + manga.getId() + "."); } } Crashlytics.log(Log.VERBOSE, "MALX", "MALManager.cleanDirtyMangaRecords(): Cleaned dirty manga records."); } } public ArrayList<History> getActivity(String username) { ArrayList<History> result = AccountService.isMAL() ? malApi.getActivity(username) : alApi.getActivity(username); Crashlytics.log(Log.INFO, "MALX", "MALManager.getActivity(): got " + String.valueOf(result != null ? result.size() : 0) + " records"); return result; } /** * Api Requests * <p/> * All the methods below this block is used to determine and make request to the API. */ public Anime getAnimeRecord(int id) { Crashlytics.log(Log.DEBUG, "MALX", "MALManager.getAnimeRecord(): Downloading " + id); return AccountService.isMAL() ? malApi.getAnime(id, 0) : alApi.getAnime(id); } public Manga getMangaRecord(int id) { Crashlytics.log(Log.DEBUG, "MALX", "MALManager.getMangaRecord(): Downloading " + id); return AccountService.isMAL() ? malApi.getManga(id, 0) : alApi.getManga(id); } public void verifyAuthentication() { if (AccountService.isMAL()) malApi.verifyAuthentication(); else if (AccountService.getAccesToken() == null) alApi.getAccesToken(); } public boolean writeAnimeDetails(Anime anime) { Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeAnimeDetails(): Updating " + anime.getId()); boolean result; if (anime.getDeleteFlag()) result = AccountService.isMAL() ? malApi.deleteAnimeFromList(anime.getId()) : alApi.deleteAnimeFromList(anime.getId()); else result = AccountService.isMAL() ? malApi.addOrUpdateAnime(anime) : alApi.addOrUpdateAnime(anime); Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeAnimeDetails(): successfully updated: " + result); return result; } public boolean writeMangaDetails(Manga manga) { Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeMangaDetails(): Updating " + manga.getId()); boolean result; if (manga.getDeleteFlag()) result = AccountService.isMAL() ? malApi.deleteMangaFromList(manga.getId()) : alApi.deleteMangaFromList(manga.getId()); else result = AccountService.isMAL() ? malApi.addOrUpdateManga(manga) : alApi.addOrUpdateManga(manga); Crashlytics.log(Log.DEBUG, "MALX", "MALManager.writeMangaDetails(): successfully updated: " + result); return result; } public BrowseList getMostPopularAnime(int page) { return AccountService.isMAL() ? malApi.getMostPopularAnime(page) : alApi.getAiringAnime(page); } public BrowseList getMostPopularManga(int page) { return AccountService.isMAL() ? malApi.getMostPopularManga(page) : alApi.getPublishingManga(page); } public BrowseList getTopRatedAnime(int page) { return AccountService.isMAL() ? malApi.getTopRatedAnime(page) : alApi.getYearAnime(Calendar.getInstance().get(Calendar.YEAR), page); } public BrowseList getTopRatedManga(int page) { return AccountService.isMAL() ? malApi.getTopRatedManga(page) : alApi.getYearManga(Calendar.getInstance().get(Calendar.YEAR), page); } public BrowseList getJustAddedAnime(int page) { return AccountService.isMAL() ? malApi.getJustAddedAnime(page) : alApi.getJustAddedAnime(page); } public BrowseList getJustAddedManga(int page) { return AccountService.isMAL() ? malApi.getJustAddedManga(page) : alApi.getJustAddedManga(page); } public BrowseList getUpcomingAnime(int page) { return AccountService.isMAL() ? malApi.getUpcomingAnime(page) : alApi.getUpcomingAnime(page); } public BrowseList getUpcomingManga(int page) { return AccountService.isMAL() ? malApi.getUpcomingManga(page) : alApi.getUpcomingManga(page); } public ArrayList<Anime> searchAnime(String query, int page) { return AccountService.isMAL() ? malApi.searchAnime(query, page) : alApi.searchAnime(query, page); } public ArrayList<Manga> searchManga(String query, int page) { return AccountService.isMAL() ? malApi.searchManga(query, page) : alApi.searchManga(query, page); } public ArrayList<Reviews> getAnimeReviews(int id, int page) { return AccountService.isMAL() ? malApi.getAnimeReviews(id, page) : alApi.getAnimeReviews(id, page); } public ArrayList<Reviews> getMangaReviews(int id, int page) { return AccountService.isMAL() ? malApi.getMangaReviews(id, page) : alApi.getMangaReviews(id, page); } public ArrayList<Forum> getForumCategories() { return AccountService.isMAL() ? malApi.getForum().createBaseModel() : ForumAL.getForum(); } public ArrayList<Forum> getCategoryTopics(int id, int page) { return AccountService.isMAL() ? malApi.getCategoryTopics(id, page).createBaseModel() : alApi.getTags(id, page).getForumListBase(); } public ArrayList<Forum> getTopic(int id, int page) { return AccountService.isMAL() ? malApi.getPosts(id, page).createBaseModel() : alApi.getPosts(id, page).convertBaseModel(); } public boolean deleteAnime(Anime anime) { return dbMan.deleteAnime(anime.getId()); } public boolean deleteManga(Manga manga) { return dbMan.deleteManga(manga.getId()); } public ArrayList<Forum> search(String query) { return AccountService.isMAL() ? malApi.search(query).createBaseModel() : alApi.search(query).getForumListBase(); } public ArrayList<Forum> getSubCategory(int id, int page) { return malApi.getSubBoards(id, page).createBaseModel(); } public boolean addComment(int id, String message) { return AccountService.isMAL() ? malApi.addComment(id, message) : alApi.addComment(id, message); } public boolean updateComment(int id, String message) { return AccountService.isMAL() ? malApi.updateComment(id, message) : alApi.updateComment(id, message); } }
package com.conveyal.r5.streets; import com.conveyal.r5.profile.Mode; import com.conveyal.r5.profile.ProfileRequest; import com.conveyal.r5.util.TIntObjectHashMultimap; import com.conveyal.r5.util.TIntObjectMultimap; import gnu.trove.iterator.TIntIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.time.Instant; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; /** * This routes over the street layer of a TransitNetwork. * It is a throw-away calculator object that retains routing state and after the search is finished. * Additional functions are called to retrieve the routing results from that state. */ public class StreetRouter { private static final Logger LOG = LoggerFactory.getLogger(StreetRouter.class); private static final boolean DEBUG_OUTPUT = false; public static final int ALL_VERTICES = -1; public final StreetLayer streetLayer; // TODO don't hardwire drive-on-right private TurnCostCalculator turnCostCalculator; /** * It uses all nonzero limit as a limit whichever gets hit first * For example if distanceLimitMeters > 0 it is used as a limit. But if it isn't * timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set * warning is shown and both are used. */ public int distanceLimitMeters = 0; public int timeLimitSeconds = 0; // TODO we might be able to make this more efficient by taking advantage of the fact that we almost always have a // single state per edge (the only time we don't is when we're in the middle of a turn restriction). TIntObjectMultimap<State> bestStatesAtEdge = new TIntObjectHashMultimap<>(); PriorityQueue<State> queue = new PriorityQueue<>((s0, s1) -> s0.weight - s1.weight); // If you set this to a non-negative number, the search will be directed toward that vertex . public int toVertex = ALL_VERTICES; /** Set individual properties here, or an entirely new request */ public ProfileRequest profileRequest = new ProfileRequest(); /** Search mode: we need a single mode, it is up to the caller to disentagle the modes set in the profile request */ public Mode mode = Mode.WALK; private RoutingVisitor routingVisitor; private Split originSplit; private Split destinationSplit; private int bestWeightAtDestination = Integer.MAX_VALUE; /** * Here is previous streetRouter in multi router search * For example if we are searching for P+R we need 2 street searches * First from start to all car parks and next from all the car parks to transit stops * <p> * Second street router has first one in previous. This is needed so the paths can be reconstructed in response **/ public StreetRouter previous; public void setRoutingVisitor(RoutingVisitor routingVisitor) { this.routingVisitor = routingVisitor; } /** Currently used for debugging snapping to vertices * TODO: API should probably be nicer * setOrigin on split or setOrigin that would return split * @return */ public Split getOriginSplit() { return originSplit; } /** * @return a map from transit stop indexes to their distances from the origin. * Note that the TransitLayer contains all the information about which street vertices are transit stops. */ public TIntIntMap getReachedStops() { TIntIntMap result = new TIntIntHashMap(); streetLayer.linkedTransitLayer.stopForStreetVertex.forEachEntry((streetVertex, stop) -> { if (streetVertex == -1) return true; State state = getStateAtVertex(streetVertex); // TODO should this be time? if (state != null) result.put(stop, state.weight); return true; // continue iteration }); return result; } /** Return a map where the keys are all the reached vertices, and the values are their distances from the origin. */ public TIntIntMap getReachedVertices () { TIntIntMap result = new TIntIntHashMap(); EdgeStore.Edge e = streetLayer.edgeStore.getCursor(); bestStatesAtEdge.forEachEntry((eidx, states) -> { if (eidx < 0) return true; State state = states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get(); e.seek(eidx); int vidx = e.getToVertex(); if (!result.containsKey(vidx) || result.get(vidx) > state.weight) result.put(vidx, state.weight); return true; // continue iteration }); return result; } /** * @return a map where all the keys are vertex indexes with the particular flag and all the values are states. */ public TIntObjectMap<State> getReachedVertices (VertexStore.VertexFlag flag) { TIntObjectMap<State> result = new TIntObjectHashMap<>(); EdgeStore.Edge e = streetLayer.edgeStore.getCursor(); VertexStore.Vertex v = streetLayer.vertexStore.getCursor(); bestStatesAtEdge.forEachEntry((eidx, states) -> { if (eidx < 0) return true; State state = states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get(); e.seek(eidx); int vidx = e.getToVertex(); v.seek(vidx); if (v.getFlag(flag)) { if (!result.containsKey(vidx) || result.get(vidx).weight > state.weight) { result.put(vidx, state); } } return true; // continue iteration }); return result; } /** * Get a distance table to all street vertices touched by the last search operation on this StreetRouter. * @return A packed list of (vertex, distance) for every reachable street vertex. * This is currently returning the weight, which is the distance in meters. */ public int[] getStopTree () { TIntIntMap states = getReachedVertices(); TIntList result = new TIntArrayList(states.size() * 2); // Convert stop vertex indexes in street layer to transit layer stop indexes. states.forEachEntry((vertexIndex, weight) -> { result.add(vertexIndex); result.add(weight); return true; // continue iteration }); return result.toArray(); } public StreetRouter (StreetLayer streetLayer) { this.streetLayer = streetLayer; this.turnCostCalculator = new TurnCostCalculator(streetLayer, true); } /** * @param lat Latitude in floating point (not fixed int) degrees. * @param lon Longitude in flating point (not fixed int) degrees. * @return true if edge was found near wanted coordinate */ public boolean setOrigin (double lat, double lon) { Split split = streetLayer.findSplit(lat, lon, 300); if (split == null) { LOG.info("No street was found near the specified origin point of {}, {}.", lat, lon); return false; } originSplit = split; bestStatesAtEdge.clear(); queue.clear(); // from vertex is at end of back edge. Set edge correctly so that turn restrictions/costs are applied correctly // at the origin. State startState0 = new State(split.vertex0, split.edge + 1, profileRequest.getFromTimeDate(), mode); State startState1 = new State(split.vertex1, split.edge, profileRequest.getFromTimeDate(), mode); // TODO walk speed, assuming 1 m/sec currently. startState0.weight = split.distance0_mm / 1000; startState1.weight = split.distance1_mm / 1000; // NB not adding to bestStates, as it will be added when it comes out of the queue queue.add(startState0); queue.add(startState1); return true; } public void setOrigin (int fromVertex) { bestStatesAtEdge.clear(); queue.clear(); // NB backEdge of -1 is no problem as it is a special case that indicates that the origin was a vertex. State startState = new State(fromVertex, -1, profileRequest.getFromTimeDate(), mode); queue.add(startState); } /** * Adds multiple origins. * * Each bike Station is one origin. Weight is copied from state. * @param bikeStations map of bikeStation vertexIndexes and states Return of {@link #getReachedVertices(VertexStore.VertexFlag)}} * @param switchTime How many ms is added to state time (this is used when switching modes, renting bike, parking a car etc.) * @param switchCost This is added to the weight and is a cost of switching modes */ public void setOrigin(TIntObjectMap<State> bikeStations, int switchTime, int switchCost) { bestStatesAtEdge.clear(); queue.clear(); bikeStations.forEachEntry((vertexIdx, bikeStationState) -> { // backEdge needs to be unique for each start state or they will wind up dominating each other. // subtract 1 from -vertexIdx because -0 == 0 State state = new State(vertexIdx, -vertexIdx - 1, bikeStationState.getTime()+switchTime, mode); state.weight = bikeStationState.weight+switchCost; state.isBikeShare = true; queue.add(state); return true; }); } public boolean setDestination (double lat, double lon) { this.destinationSplit = streetLayer.findSplit(lat, lon, 300); return this.destinationSplit != null; } public void setDestination (Split split) { this.destinationSplit = split; } /** * Call one of the setOrigin functions first. * * It uses all nonzero limit as a limit whichever gets hit first * For example if distanceLimitMeters > 0 it is used a limit. But if it isn't * timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set * warning is shown and both are used. */ public void route () { final int distanceLimitMm; //This is needed otherwise timeLimitSeconds gets changed and // on next call of route on same streetRouter wrong warnings are returned // (since timeLimitSeconds is MAX_INTEGER not 0) final int tmpTimeLimitSeconds; if (distanceLimitMeters > 0) { //Distance in State is in mm wanted distance is in meters which means that conversion is necessary distanceLimitMm = distanceLimitMeters * 1000; } else { //We need to set distance limit to largest possible value otherwise nothing would get routed //since first edge distance would be larger then 0 m and routing would stop distanceLimitMm = Integer.MAX_VALUE; } if (timeLimitSeconds > 0) { tmpTimeLimitSeconds = timeLimitSeconds; } else { //Same issue with time limit tmpTimeLimitSeconds = Integer.MAX_VALUE; } if (timeLimitSeconds > 0 && distanceLimitMeters > 0) { LOG.warn("Both distance limit of {}m and time limit of {}s are set in streetrouter", distanceLimitMeters, timeLimitSeconds); } else if (timeLimitSeconds == 0 && distanceLimitMeters == 0) { LOG.warn("Distance and time limit are set to 0 in streetrouter. This means NO LIMIT in searching so WHOLE of street graph will be searched. This can be slow."); } else if (distanceLimitMeters > 0) { LOG.debug("Using distance limit of {}m", distanceLimitMeters); } else if (timeLimitSeconds > 0) { LOG.debug("Using time limit of {}s", timeLimitSeconds); } if (queue.size() == 0) { LOG.warn("Routing without first setting an origin, no search will happen."); } PrintStream printStream = null; // for debug output if (DEBUG_OUTPUT) { File debugFile = new File(String.format("street-router-debug.csv")); OutputStream outputStream; try { outputStream = new BufferedOutputStream(new FileOutputStream(debugFile)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } printStream = new PrintStream(outputStream); printStream.println("lat,lon,weight"); } EdgeStore.Edge edge = streetLayer.edgeStore.getCursor(); QUEUE: while (!queue.isEmpty()) { State s0 = queue.poll(); if (DEBUG_OUTPUT) { VertexStore.Vertex v = streetLayer.vertexStore.getCursor(s0.vertex); double lat = v.getLat(); double lon = v.getLon(); if (s0.backEdge != -1) { EdgeStore.Edge e = streetLayer.edgeStore.getCursor(s0.backEdge); v.seek(e.getFromVertex()); lat = (lat + v.getLat()) / 2; lon = (lon + v.getLon()) / 2; } printStream.println(String.format("%.6f,%.6f,%d", v.getLat(), v.getLon(), s0.weight)); } if (bestStatesAtEdge.containsKey(s0.backEdge)) { for (State state : bestStatesAtEdge.get(s0.backEdge)) { // states in turn restrictions don't dominate anything if (state.turnRestrictions == null) continue QUEUE; else if (s0.turnRestrictions != null && s0.turnRestrictions.size() == state.turnRestrictions.size()) { // if they have the same turn restrictions, dominate this state with the one in the queue. // if we make all turn-restricted states strictly incomparable we can get infinite loops with adjacent turn // restrictions, see boolean[] same = new boolean [] { true }; s0.turnRestrictions.forEachEntry((ridx, pos) -> { if (!state.turnRestrictions.containsKey(ridx) || state.turnRestrictions.get(ridx) != pos) same[0] = false; return same[0]; // shortcut iteration if they're not the same }); if (same[0]) continue QUEUE; } } } if (toVertex > 0 && toVertex == s0.vertex) { // found destination break; } if (s0.weight > bestWeightAtDestination) break; // non-dominated state coming off the pqueue is by definition the best way to get to that vertex // but states in turn restrictions don't dominate anything, to avoid resource limiting issues if (s0.turnRestrictions != null) bestStatesAtEdge.put(s0.backEdge, s0); else { // we might need to save an existing state that is in a turn restriction so is codominant for (Iterator<State> it = bestStatesAtEdge.get(s0.backEdge).iterator(); it.hasNext();) { State other = it.next(); if (s0.weight < other.weight) it.remove(); // avoid a ton of codominant states when there is e.g. duplicated OSM data // However, save this state if it is not in a turn restriction and the other state is else if (s0.weight == other.weight && !(other.turnRestrictions != null && s0.turnRestrictions == null)) continue QUEUE; } bestStatesAtEdge.put(s0.backEdge, s0); } if (routingVisitor != null) { routingVisitor.visitVertex(s0); } // if this state is at the destination, figure out the cost at the destination and use it for target pruning // by using getState(split) we include turn restrictions and turn costs. We've already addded this state // to bestStates so getState will be correct if (destinationSplit != null && (s0.vertex == destinationSplit.vertex0 || s0.vertex == destinationSplit.vertex1)) { State atDest = getState(destinationSplit); // atDest could be null even though we've found a nearby vertex because of a turn restriction if (atDest != null && bestWeightAtDestination > atDest.weight) bestWeightAtDestination = atDest.weight; } // explore edges leaving this vertex streetLayer.outgoingEdges.get(s0.vertex).forEach(eidx -> { edge.seek(eidx); State s1 = edge.traverse(s0, mode, profileRequest, turnCostCalculator); if (s1 != null && s1.distance <= distanceLimitMm && s1.getDurationSeconds() < tmpTimeLimitSeconds) { queue.add(s1); } return true; // iteration over edges should continue }); } if (DEBUG_OUTPUT) { printStream.close(); } } /** get a single best state at the end of an edge. There can be more than one state at the end of an edge due to turn restrictions */ public State getStateAtEdge (int edgeIndex) { Collection<State> states = bestStatesAtEdge.get(edgeIndex); if (states.isEmpty()) { return null; // Unreachable } // get the lowest weight, even if it's in the middle of a turn restriction return states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get(); } /** * Get a single best state at a vertex. NB this should not be used for propagating to samples, as you need to apply * turn costs/restrictions during propagation. */ public State getStateAtVertex (int vertexIndex) { State ret = null; for (TIntIterator it = streetLayer.incomingEdges.get(vertexIndex).iterator(); it.hasNext();) { int eidx = it.next(); State state = getStateAtEdge(eidx); if (state == null) continue; if (ret == null) ret = state; else if (ret.weight > state.weight) ret = state; } return ret; } public int getTravelTimeToVertex (int vertexIndex) { State state = getStateAtVertex(vertexIndex); return state != null ? state.weight : Integer.MAX_VALUE; } /** * Returns state with smaller weight to vertex0 or vertex1 * * If state to only one vertex exists return that vertex. * If state to none of the vertices exists returns null * @param split * @return */ public State getState(Split split) { // get all the states at all the vertices List<State> relevantStates = new ArrayList<>(); EdgeStore.Edge e = streetLayer.edgeStore.getCursor(split.edge); for (TIntIterator it = streetLayer.incomingEdges.get(split.vertex0).iterator(); it.hasNext();) { Collection<State> states = bestStatesAtEdge.get(it.next()); states.stream().filter(s -> e.canTurnFrom(s, new State(-1, split.edge, 0, s))) .map(s -> { State ret = new State(-1, split.edge, 0, s); ret.mode = s.mode; // figure out the turn cost int turnCost = this.turnCostCalculator.computeTurnCost(s.backEdge, split.edge, s.mode); int traversalCost = (int) Math.round(split.distance0_mm / 1000d / e.calculateSpeed(profileRequest, s.mode, 0)); // TODO length of perpendicular ret.incrementWeight(turnCost + traversalCost); ret.incrementTimeInSeconds(turnCost + traversalCost); return ret; }) .forEach(relevantStates::add); } // advance to back edge e.advance(); for (TIntIterator it = streetLayer.incomingEdges.get(split.vertex1).iterator(); it.hasNext();) { Collection<State> states = bestStatesAtEdge.get(it.next()); states.stream().filter(s -> e.canTurnFrom(s, new State(-1, split.edge + 1, 0, s))) .map(s -> { State ret = new State(-1, split.edge + 1, 0, s); ret.mode = s.mode; // figure out the turn cost int turnCost = this.turnCostCalculator.computeTurnCost(s.backEdge, split.edge + 1, s.mode); int traversalCost = (int) Math.round(split.distance1_mm / 1000d / e.calculateSpeed(profileRequest, s.mode, 0)); // TODO length of perpendicular ret.incrementWeight(turnCost + traversalCost); ret.incrementTimeInSeconds(turnCost + traversalCost); return ret; }) .forEach(relevantStates::add); } return relevantStates.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).orElse(null); } public Split getDestinationSplit() { return destinationSplit; } public static class State implements Cloneable { public int vertex; public int weight; public int backEdge; // the current time at this state, in milliseconds UNIX time public long time; protected int durationSeconds; //Distance in mm public int distance; public Mode mode; public State backState; // previous state in the path chain public boolean isBikeShare = false; //is true if vertex in this state is Bike sharing station where mode switching occurs /** * turn restrictions we are in the middle of. * Value is how many edges of this turn restriction we have traversed so far, so if 1 we have traversed only the from edge, etc. */ public TIntIntMap turnRestrictions; public State(int atVertex, int viaEdge, long fromTimeDate, State backState) { this.vertex = atVertex; this.backEdge = viaEdge; this.backState = backState; this.time = fromTimeDate; this.distance = backState.distance; this.durationSeconds = backState.durationSeconds; this.weight = backState.weight; } public State(int atVertex, int viaEdge, long fromTimeDate, Mode mode) { this.vertex = atVertex; this.backEdge = viaEdge; this.backState = null; this.distance = 0; this.mode = mode; this.durationSeconds = 0; this.time = fromTimeDate; } public void incrementTimeInSeconds(long seconds) { if (seconds < 0) { LOG.warn("A state's time is being incremented by a negative amount while traversing edge " ); //defectiveTraversal = true; return; } durationSeconds += seconds; time += seconds*1000; } public int getDurationSeconds() { return durationSeconds; } public long getTime() { return time; } public void incrementWeight(float weight) { this.weight+=(int)weight; } public String dump() { State state = this; StringBuilder out = new StringBuilder(); out.append("BEGIN PATH DUMP\n"); while (state != null) { out.append(String.format("%s at %s via %s\n", state.vertex, state.weight, state.backEdge)); state = state.backState; } out.append("END PATH DUMP\n"); return out.toString(); } } }
package com.crystalcraftmc.pvpstorm; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import java.io.IOException; import java.util.Collection; public class PvPStorm extends JavaPlugin { // TODO Implement mob boss health bar - perhaps in listener? NEEDS RESEARCH. public void onEnable() { getLogger().info(ChatColor.AQUA + "PvPStorm has been initialized!"); try { MetricsLite metrics = new MetricsLite(this); metrics.start(); } catch (IOException e) { // Failed to submit the stats :-( } getServer().getPluginManager().registerEvents(gameStart, this); getServer().getPluginManager().registerEvents(gameEnd, this); } public void onDisable() { getLogger().info(ChatColor.RED + "PvPStorm has been stopped by the server."); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("storm")) { if (!(sender instanceof Player)) { sender.sendMessage("This command can only be run by a player."); return false; } else if (args.length < 1) { return false; } else if (args.length >= 1) { Player p = (Player) sender; World world = p.getWorld(); if (args[0].equalsIgnoreCase("start")) { Bukkit.broadcastMessage(ChatColor.DARK_RED + getConfig().getString("start-message")); world.setStorm(true); this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { Bukkit.broadcastMessage(ChatColor.DARK_RED + "The PvP Storm is now hitting the Arena!"); } }, 12000L); // 12000L == 10 minutes, 60L == 3 seconds, 20L == 1 second (it's the # of ticks) // TODO Alert the listener to begin counting who hits the Stormer, in order to give prizes at end return true; } else if (args[0].equalsIgnoreCase("stop")) { Bukkit.broadcastMessage(ChatColor.AQUA + getConfig().getString("end-message")); world.setStorm(false); // TODO Alert listener to stop counting and give out awards return true; } else if (args[0].equalsIgnoreCase("power")) { if (args.length < 2) { sender.sendMessage(ChatColor.YELLOW + "The available Storm powers are:" + ChatColor.RED + "/storm power flare" + ChatColor.GRAY + "/storm power vanish" + ChatColor.AQUA + "/storm power timewarp"); return true; } else if (args[1].equalsIgnoreCase("flare")) { Collection<? extends Player> players = Bukkit.getOnlinePlayers(); Location senderLoc = p.getLocation(); Location nearbyLoc; Bukkit.broadcastMessage(p.getDisplayName() + ChatColor.YELLOW + " used " + ChatColor.GOLD + " FLARE " + ChatColor.YELLOW + " ability!"); for (Player nearbyPlayer : players) { if (nearbyPlayer.getLocation().distanceSquared(senderLoc) <= 25) { nearbyLoc = nearbyPlayer.getLocation(); nearbyPlayer.setHealth(nearbyPlayer.getHealth() - 2.0); nearbyPlayer.playSound(nearbyLoc, Sound.SUCCESSFUL_HIT, 1, 1); } p.playSound(senderLoc, Sound.EXPLODE, 1, 1); } if (p.getHealth() > 3.0) p.setHealth(p.getHealth() - 3.0); else if (p.getHealth() <= 1.0) { p.setHealth(0.0D); Bukkit.broadcastMessage(p.getDisplayName() + ChatColor.RED + "commit suicide with their own powers!"); } else p.setHealth(1.0); return true; } else if (args[1].equalsIgnoreCase("vanish")) { Bukkit.broadcastMessage(p.getDisplayName() + ChatColor.YELLOW + " used " + ChatColor.GRAY + " VANISH " + ChatColor.YELLOW + " ability!"); p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 3600, 0, false, false)); if (p.getHealth() > 5.0) p.setHealth(p.getHealth() - 5.0); else if (p.getHealth() <= 1.0) { p.setHealth(0.0D); Bukkit.broadcastMessage(p.getDisplayName() + ChatColor.RED + "commit suicide with their own powers!"); } else p.setHealth(1.0); return true; } else if (args[1].equalsIgnoreCase("timewarp")) { Vector direction = p.getLocation().getDirection(); Bukkit.broadcastMessage(p.getDisplayName() + ChatColor.YELLOW + " used " + ChatColor.RED + " TIMEWARP " + ChatColor.YELLOW + " ability!"); p.setVelocity(new Vector(direction.getX() * -2.5, 1.2, direction.getZ() * -2.5)); p.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 300, 0)); return true; } } else { return false; } } } return false; } private final GameStartListener gameStart = new GameStartListener(this); private final GameEndListener gameEnd = new GameEndListener(this); }
package com.github.davidmoten.tj; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; public class TileFactory { private static final Logger log = LoggerFactory .getLogger(TileFactory.class); public static final int TILE_SIZE = 256; private final String mapType; public TileFactory(String mapType) { this.mapType = mapType; } public static class Coverage { private final List<TileUrl> tiles; private final int minIndexX; private final int maxIndexX; private final int minIndexY; private final int deltaX; private final int deltaY; private final int scaledTileSize; public Coverage(List<TileUrl> tiles, int deltaX, int deltaY, int scaledTileSize) { Preconditions.checkArgument(!tiles.isEmpty(), "tiles is empty!"); this.tiles = tiles; this.deltaX = deltaX; this.deltaY = deltaY; this.scaledTileSize = scaledTileSize; this.minIndexX = getMinIndexX(tiles); this.maxIndexX = getMaxIndexX(tiles); this.minIndexY = getMinIndexY(tiles); } private static int getMaxIndexX(List<TileUrl> tiles) { Integer max = null; for (final TileUrl tile : tiles) { if (max == null || max < tile.getTile().getIndex().getX()) max = tile.getTile().getIndex().getX(); } return max; } private static int getMinIndexX(List<TileUrl> tiles) { Integer min = null; for (final TileUrl tile : tiles) { if (min == null || min > tile.getTile().getIndex().getX()) min = tile.getTile().getIndex().getX(); } return min; } private static int getMinIndexY(List<TileUrl> tiles) { Integer min = null; for (final TileUrl tile : tiles) { if (min == null || min > tile.getTile().getIndex().getY()) min = tile.getTile().getIndex().getY(); } return min; } public List<TileUrl> getTiles() { return tiles; } public int getMinIndexX() { return minIndexX; } public int getMaxIndexX() { return maxIndexX; } public int getMinIndexY() { return minIndexY; } public int getDeltaX() { return deltaX; } public int getDeltaY() { return deltaY; } public int getScaledTileSize() { return scaledTileSize; } } public Coverage getCoverage(double topLat, double leftLon, double rightLon, int width, int height) { final double diffLon = Math.abs(leftLon - rightLon); final int zoom = calculateZoom(width, diffLon); final TileIndex index1 = getIndexFor(topLat, leftLon, zoom); final int xIndex2 = lonToTileIndexX(rightLon, zoom); final int minIndexX = index1.getX(); final int minIndexY = index1.getY(); final int maxIndexX = xIndex2; final int deltaY = TileFactory.latToYInTile(topLat, zoom); final int deltaX = TileFactory.lonToXInTile(leftLon, zoom); final int deltaX2 = TileFactory.lonToXInTile(rightLon, zoom); final int tilesAcross = maxIndexX - minIndexX + 1; final int scaledTileSize = (int) Math .round((width) / (tilesAcross - 1 - (double) deltaX / TILE_SIZE + (double) deltaX2 / TILE_SIZE)); log.info("deltaX=" + deltaX + ",deltaX2=" + deltaX2 + "," + "minIndexX=" + minIndexX + ", maxIndexX=" + maxIndexX + ",scaledTileSize=" + scaledTileSize); // scaledTileSize = scaledTileSize * 11 / 10; final int maxIndexY = minIndexY + height / scaledTileSize + 1; final List<Tile> tiles = new ArrayList<>(); for (int x = minIndexX; x <= maxIndexX; x++) for (int y = minIndexY; y <= maxIndexY; y++) { tiles.add(new Tile(new TileIndex(x, y), zoom)); } final List<TileUrl> tileUrls = new ArrayList<>(); for (final Tile tile : tiles) { tileUrls.add(new TileUrl(tile, toUrl(tile, mapType))); } return new Coverage(tileUrls, deltaX, deltaY, scaledTileSize); } private static int calculateZoom(int width, final double diffLon) { return (int) (Math.round(Math.floor(Math.log(360.0 * width / diffLon / TILE_SIZE) / Math.log(2))) + 1); } private static String toUrl(Tile tile, String mapType) { final int maxIndexX = (int) Math.pow(2, tile.getZoom()); return String.format( "https://mts1.google.com/vt/lyrs=%s&x=%s&y=%s&z=%s", mapType, tile.getIndex().getX() % maxIndexX, tile.getIndex().getY(), tile.getZoom()); } static TileIndex getIndexFor(double lat, double lon, int zoom) { if (lat < -90 || lat > 90) throw new IllegalArgumentException("lat must be in range -90 to 90"); final int tilex = lonToTileIndexX(lon, zoom); final int tiley = latToTileY(lat, zoom); return new TileIndex(tilex, tiley); } private static int lonToTileIndexX(double lon, int zoom) { if (lon < -180 || lon > 180) throw new IllegalArgumentException( "lon must be in range -180 to 180"); // correct the longitude to go from 0 to 360 lon = 180 + lon; // find tile size from zoom level final double longTileSize = 360 / (Math.pow(2, zoom)); // find the tile coordinates return (int) Math.round(Math.floor(lon / longTileSize)); } private static int latToTileY(double lat, int zoom) { final double y = latToY(lat, zoom); return (int) y / 256; } public static int latToYInTile(double lat, int zoom) { final double y = latToY(lat, zoom); return (int) Math.round(Math.floor(y - TILE_SIZE * ((int) y / 256))); } public static int lonToXInTile(double lon, int zoom) { final double longTileSize = 360 / (Math.pow(2, zoom)); // find the tile coordinates return (int) Math.round(TILE_SIZE * (lon / longTileSize - Math.floor(lon / longTileSize))); } private static double latToY(double lat, int zoom) { Double exp = Math.sin(lat * Math.PI / 180); if (exp < -.9999) exp = -.9999; else if (exp > .9999) exp = .9999; final double y = (Math.round(TILE_SIZE * (Math.pow(2, zoom - 1))) + ((.5 * Math .log((1 + exp) / (1 - exp))) * ((-TILE_SIZE * (Math .pow(2, zoom))) / (2 * Math.PI)))); return y; } }
package com.github.semres.gui; import com.github.semres.EdgeEdit; import com.github.semres.SynsetUpdate; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.Label; import javafx.scene.control.TitledPane; import javafx.scene.layout.GridPane; import java.io.IOException; public class EdgeMergePanel extends TitledPane { @FXML private GridPane gridPane; @FXML private Label relationTypesLabel; @FXML private Label originalRelationTypeLabel; @FXML private Label finalRelationTypeLabel; @FXML private Button cancelRelationReplaceButton; @FXML private Label descriptionLabel; @FXML private Label originalDescriptionLabel; @FXML private Label finalDescriptionLabel; @FXML private ButtonBar descriptionButtonBar; @FXML private Button mergeDescriptionButton; @FXML private Label weightLabel; @FXML private Label originalWeightLabel; @FXML private Label finalWeightLabel; @FXML private Button cancelWeightReplaceButton; @FXML private Button cancelButton; private SynsetUpdate synsetUpdate; private EdgeEdit edgeEdit; private UpdatesListController parentController; public EdgeMergePanel(SynsetUpdate synsetUpdate, EdgeEdit edgeEdit, UpdatesListController parentController) { this.synsetUpdate = synsetUpdate; FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/edge-merge.fxml")); loader.setRoot(this); loader.setController(this); try { loader.load(); } catch (IOException e) { throw new RuntimeException(e); } this.parentController = parentController; this.edgeEdit = edgeEdit; this.textProperty().setValue( synsetUpdate.getOriginalSynset().getRepresentation() + " → " + synsetUpdate.getPointedSynset(edgeEdit.getOriginal()).getRepresentation()); String original = edgeEdit.getOriginal().getRelationType().getType(); String edited = edgeEdit.getEdited().getRelationType().getType(); if (!original.equals(edited)) { originalRelationTypeLabel.setText(original); finalRelationTypeLabel.setText(edited); } else { removeRelationTypeRow(); } original = Double.toString(edgeEdit.getOriginal().getWeight()); edited = Double.toString(edgeEdit.getEdited().getWeight()); if (!original.equals(edited)) { originalWeightLabel.setText(original); finalWeightLabel.setText(edited); } else { removeWeightRow(); } original = nullOrEmpty(edgeEdit.getOriginal().getDescription()) ? "No description" : edgeEdit.getOriginal().getDescription(); edited = nullOrEmpty(edgeEdit.getEdited().getDescription()) ? "No description" : edgeEdit.getEdited().getDescription(); if (!original.equals(edited)) { originalDescriptionLabel.setText(original); finalDescriptionLabel.setText(edited); if (original.equals("No description")) { mergeDescriptionButton.setVisible(false); mergeDescriptionButton.setManaged(false); } } else { removeDescriptionRow(); } } public EdgeEdit getEdgeEdit() { return edgeEdit; } public SynsetUpdate getSynsetUpdate() { return synsetUpdate; } public void cancelRelationReplace() { synsetUpdate.cancelEdgeRelationTypeChange(edgeEdit.getOriginal().getId()); removeRelationTypeRow(); if (noMoreChanges()) { removeItself(); } } private void removeRelationTypeRow() { gridPane.getChildren().remove(relationTypesLabel); gridPane.getChildren().remove(originalRelationTypeLabel); gridPane.getChildren().remove(finalRelationTypeLabel); gridPane.getChildren().remove(cancelRelationReplaceButton); } public void mergeDescription() { synsetUpdate.mergeEdgeDescriptions(edgeEdit.getOriginal().getId()); descriptionButtonBar.getButtons().remove(mergeDescriptionButton); } public void cancelDescriptionReplace() { synsetUpdate.cancelEdgeDescriptionChange(edgeEdit.getOriginal().getId()); removeDescriptionRow(); if (noMoreChanges()) { removeItself(); } } private void removeDescriptionRow() { gridPane.getChildren().remove(descriptionLabel); gridPane.getChildren().remove(originalDescriptionLabel); gridPane.getChildren().remove(finalDescriptionLabel); gridPane.getChildren().remove(descriptionButtonBar); } public void cancelWeightReplace() { synsetUpdate.cancelEdgeWeightChange(edgeEdit.getOriginal().getId()); removeWeightRow(); if (noMoreChanges()) { removeItself(); } } private void removeWeightRow() { gridPane.getChildren().remove(weightLabel); gridPane.getChildren().remove(originalWeightLabel); gridPane.getChildren().remove(finalWeightLabel); gridPane.getChildren().remove(cancelWeightReplaceButton); } private boolean noMoreChanges() { return !gridPane.getChildren().contains(relationTypesLabel) && !gridPane.getChildren().contains(descriptionLabel) && !gridPane.getChildren().contains(weightLabel); } public void removeItself() { parentController.cancelEdgeMerge(this); } private boolean nullOrEmpty(String string) { return string == null || string.isEmpty(); } }
package com.google.sps.data; import java.util.List; import java.util.LinkedList; /** SmallCityService object representing all components of the webapp **/ public class SmallCityService { private User user; private List<Listing> businesses; /** Create a new Small City Service instance from with no information **/ public SmallCityService() { } /** * Create User instance from zipCode and get businesses list * @param zipCode inputted zipcode of user **/ public void createWithZip(String zipCode) { this.user = new User(zipCode); findAllBusinesses(); eliminateBigBusinesses(); } /** * Create User instance from geolocation and get businesses list * @param mapLocation found geolocation of user **/ public void createWithGeolocation(MapLocation mapLocation) { this.user = new User(mapLocation); findAllBusinesses(); eliminateBigBusinesses(); } public void findAllBusinesses() { // TODO: Get businesses from Place API given user location businesses = new LinkedList<Listing>(); businesses.add(new Listing("LA Fitness", new MapLocation(40.457091, -79.915331), 3.9, null, "https: businesses.add(new Listing("west elm", new MapLocation(40.456279, -79.915015), 3.6, null, "https: businesses.add(new Listing("McDonalds", new MapLocation(40.459450, -79.918479), 2.6, null, "https: businesses.add(new Listing("East End Brewing Company", new MapLocation(40.459391, -79.911782), 4.7, "https: businesses.add(new Listing("The Shiny Bean Coffee & Tea", new MapLocation(40.496328, -79.944862), 4.9, "https: businesses.add(new Listing("Weisshouse", new MapLocation(40.456684, -79.925499), 4.3, "https: } public void eliminateBigBusinesses() { // TODO: Parse big business list and remove big businesses from businessList } public List<Listing> getBusinesses() { return businesses; } }
package com.jcabi.aspects.aj; import com.jcabi.log.Logger; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.validation.Constraint; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Path; import javax.validation.Valid; import javax.validation.Validation; import javax.validation.ValidationException; import javax.validation.Validator; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.metadata.ConstraintDescriptor; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.ConstructorSignature; import org.aspectj.lang.reflect.MethodSignature; @Aspect @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.TooManyMethods" }) public final class MethodValidator { /** * JSR-303 Validator. */ private final transient Validator validator = MethodValidator.build(); /** * Validate arguments of a method. * * <p>Try NOT to change the signature of this method, in order to keep * it backward compatible. * * @param point Join point * @checkstyle LineLength (3 lines) */ @Before("execution(* *(.., @(javax.validation.* || javax.validation.constraints.*) (*), ..))") public void beforeMethod(final JoinPoint point) { if (this.validator != null) { this.validate( point, MethodSignature.class.cast(point.getSignature()) .getMethod() .getParameterAnnotations() ); } } /** * Validate arguments of constructor. * * <p>Try NOT to change the signature of this method, in order to keep * it backward compatible. * * @param point Join point * @checkstyle LineLength (3 lines) */ @Before("preinitialization(*.new(.., @(javax.validation.* || javax.validation.constraints.*) (*), ..))") public void beforeCtor(final JoinPoint point) { if (this.validator != null) { this.validate( point, ConstructorSignature.class.cast(point.getSignature()) .getConstructor() .getParameterAnnotations() ); } } /** * Validate method response. * * <p>Try NOT to change the signature of this method, in order to keep * it backward compatible. * * @param point Join point * @param result Result of the method * @checkstyle LineLength (4 lines) * @since 0.7.11 */ @AfterReturning( pointcut = "execution(@(javax.validation.* || javax.validation.constraints.*) * *(..))", returning = "result" ) public void after(final JoinPoint point, final Object result) { final Method method = MethodSignature.class.cast( point.getSignature() ).getMethod(); if (method.isAnnotationPresent(NotNull.class) && result == null && !method.getReturnType().equals(Void.TYPE)) { throw new ConstraintViolationException( method.getAnnotation(NotNull.class).message(), new HashSet<ConstraintViolation<?>>( Collections.<ConstraintViolation<?>>singletonList( MethodValidator.violation( result, method.getAnnotation(NotNull.class).message() ) ) ) ); } if (method.isAnnotationPresent(Valid.class) && result != null) { final Set<ConstraintViolation<Object>> violations = this.validate(result); if (!violations.isEmpty()) { throw new ConstraintViolationException(violations); } } } /** * Validate method at the given point. * @param point Join point * @param params Parameters (their annotations) */ private void validate(final JoinPoint point, final Annotation[][] params) { final Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(0); for (int pos = 0; pos < params.length; ++pos) { violations.addAll( this.validate(pos, point.getArgs()[pos], params[pos]) ); } if (!violations.isEmpty()) { throw new ConstraintViolationException( MethodValidator.pack(violations), violations ); } } /** * Validate one method argument against its annotations. * @param pos Position of the argument in method signature * @param arg The argument * @param annotations Array of annotations * @return A set of violations * @todo #61 It's a temporary design, which enables only NotNull, * Valid, and Pattern annotations. In the future we should use * JSR-303 Validator, when they implement validation of values (see * their appendix C). */ private Set<ConstraintViolation<?>> validate(final int pos, final Object arg, final Annotation[] annotations) { final Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>(0); for (final Annotation antn : annotations) { if (antn.annotationType().equals(NotNull.class)) { if (arg == null) { violations.add( MethodValidator.violation( String.format("param #%d", pos), NotNull.class.cast(antn).message() ) ); } } else if (antn.annotationType().equals(Valid.class) && arg != null) { violations.addAll(this.validate(arg)); } else if (antn.annotationType().equals(Pattern.class)) { if (arg != null && !arg.toString() .matches(Pattern.class.cast(antn).regexp())) { violations.add( MethodValidator.violation( String.format("param #%d '%s'", pos, arg), Pattern.class.cast(antn).message() ) ); } } else if (antn.annotationType() .isAnnotationPresent(Constraint.class)) { Logger.warn( this, "%[type]s annotation is not supported at the moment", antn.annotationType() ); } } return violations; } /** * Create one simple violation. * @param arg The argument passed * @param msg Error message to show * @return The violation */ private static ConstraintViolation<?> violation(final Object arg, final String msg) { // @checkstyle AnonInnerLength (50 lines) return new ConstraintViolation<String>() { @Override public String toString() { return String.format("%s %s", arg, msg); } @Override public ConstraintDescriptor<?> getConstraintDescriptor() { return null; } @Override public Object getInvalidValue() { return arg; } @Override public Object getLeafBean() { return null; } @Override public String getMessage() { return msg; } @Override public String getMessageTemplate() { return msg; } @Override public Path getPropertyPath() { return null; } @Override public String getRootBean() { return ""; } @Override public Class<String> getRootBeanClass() { return String.class; } @Override public Object[] getExecutableParameters() { return new Object[0]; } @Override public Object getExecutableReturnValue() { return null; } @Override public <U> U unwrap(final Class<U> type) { return null; } }; } /** * Pack violations into string. * @param errs All violations * @return The full text */ private static String pack(final Collection<ConstraintViolation<?>> errs) { final StringBuilder text = new StringBuilder(0); for (final ConstraintViolation<?> violation : errs) { if (text.length() > 0) { text.append("; "); } text.append(violation.getMessage()); } return text.toString(); } /** * Build validator. * @return Validator to use in the singleton */ @SuppressWarnings("PMD.AvoidCatchingThrowable") private static Validator build() { Validator val = null; try { val = Validation.buildDefaultValidatorFactory().getValidator(); Logger.info( MethodValidator.class, // @checkstyle LineLength (1 line) "JSR-303 validator %[type]s instantiated by jcabi-aspects ${project.version}/${buildNumber}", val ); } catch (final ValidationException ex) { Logger.error( MethodValidator.class, // @checkstyle LineLength (1 line) "JSR-303 validator failed to initialize: %s (see http://aspects.jcabi.com/jsr-303.html)", ex.getMessage() ); } catch (final Throwable ex) { Logger.error( MethodValidator.class, "JSR-303 validator thrown during initialization: %[exception]s", ex ); } return val; } /** * Check validity of an object, when it is annotated with {@link Valid}. * @param object The object to validate * @return Found violations * @param <T> Type of violations */ @SuppressWarnings("PMD.AvoidCatchingThrowable") private <T> Set<ConstraintViolation<T>> validate(final T object) { Set<ConstraintViolation<T>> violations; try { violations = this.validator.validate(object); } catch (final Throwable ex) { Logger.error( this, // @checkstyle LineLength (1 line) "JSR-303 validator %[type]s thrown %s while validating %[type]s", this.validator, ex, object ); violations = new HashSet<ConstraintViolation<T>>(0); } return violations; } }
package com.julienvey.trello.impl; import static com.julienvey.trello.impl.TrelloUrl.ADD_CHECKITEMS_TO_CHECKLIST; import static com.julienvey.trello.impl.TrelloUrl.ADD_COMMENT_TO_CARD; import static com.julienvey.trello.impl.TrelloUrl.ADD_LABEL_TO_CARD; import static com.julienvey.trello.impl.TrelloUrl.ADD_ATTACHMENT_TO_CARD; import static com.julienvey.trello.impl.TrelloUrl.CREATE_CARD; import static com.julienvey.trello.impl.TrelloUrl.CREATE_CHECKLIST; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_BOARD; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_CARD; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_ENTITIES; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_LIST; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_MEMBER; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_MEMBER_CREATOR; import static com.julienvey.trello.impl.TrelloUrl.GET_ACTION_ORGANIZATION; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_ACTIONS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_CARD; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_CARDS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_CHECKLISTS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_LABELS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_LISTS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_MEMBERS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_MEMBERSHIPS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_MEMBER_CARDS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_MYPREFS; import static com.julienvey.trello.impl.TrelloUrl.GET_BOARD_ORGANIZATION; import static com.julienvey.trello.impl.TrelloUrl.GET_CARD; import static com.julienvey.trello.impl.TrelloUrl.GET_CARD_ACTIONS; import static com.julienvey.trello.impl.TrelloUrl.GET_CARD_ATTACHMENT; import static com.julienvey.trello.impl.TrelloUrl.GET_CARD_ATTACHMENTS; import static com.julienvey.trello.impl.TrelloUrl.GET_CARD_BOARD; import static com.julienvey.trello.impl.TrelloUrl.GET_CARD_CHECKLIST; import static com.julienvey.trello.impl.TrelloUrl.GET_CHECK_LIST; import static com.julienvey.trello.impl.TrelloUrl.GET_LIST; import static com.julienvey.trello.impl.TrelloUrl.GET_LIST_CARDS; import static com.julienvey.trello.impl.TrelloUrl.GET_MEMBER; import static com.julienvey.trello.impl.TrelloUrl.GET_MEMBER_ACTIONS; import static com.julienvey.trello.impl.TrelloUrl.GET_MEMBER_BOARDS; import static com.julienvey.trello.impl.TrelloUrl.GET_ORGANIZATION_BOARD; import static com.julienvey.trello.impl.TrelloUrl.GET_ORGANIZATION_MEMBER; import static com.julienvey.trello.impl.TrelloUrl.UPDATE_CARD; import static com.julienvey.trello.impl.TrelloUrl.createUrl; import com.julienvey.trello.domain.Label; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.julienvey.trello.ListNotFoundException; import com.julienvey.trello.NotFoundException; import com.julienvey.trello.TrelloBadRequestException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import com.julienvey.trello.Trello; import com.julienvey.trello.TrelloHttpClient; import com.julienvey.trello.domain.Action; import com.julienvey.trello.domain.Argument; import com.julienvey.trello.domain.Attachment; import com.julienvey.trello.domain.Board; import com.julienvey.trello.domain.Card; import com.julienvey.trello.domain.CardWithActions; import com.julienvey.trello.domain.CheckItem; import com.julienvey.trello.domain.CheckList; import com.julienvey.trello.domain.Entity; import com.julienvey.trello.domain.Member; import com.julienvey.trello.domain.MyPrefs; import com.julienvey.trello.domain.Organization; import com.julienvey.trello.domain.TList; import com.julienvey.trello.impl.domaininternal.Comment; import com.julienvey.trello.impl.http.ApacheHttpClient; import com.julienvey.trello.impl.http.RestTemplateHttpClient; import com.julienvey.trello.utils.ArgUtils; public class TrelloImpl implements Trello { private TrelloHttpClient httpClient; private String applicationKey; private String accessToken; private static Logger logger = LoggerFactory.getLogger(TrelloImpl.class); /** * Deprecated - use another constructor which accepts an instance of `TrelloHttpClient` instead of creating * one that is tied to Spring Web Framework. * * @see #TrelloImpl(String, String, TrelloHttpClient) */ @Deprecated public TrelloImpl(String applicationKey, String accessToken) { this(applicationKey, accessToken, new RestTemplateHttpClient()); } public TrelloImpl(String applicationKey, String accessToken, TrelloHttpClient httpClient) { this.applicationKey = applicationKey; this.accessToken = accessToken; this.httpClient = httpClient; } /* Boards */ @Override public Board getBoard(String boardId, Argument... args) { Board board = get(createUrl(GET_BOARD).params(args).asString(), Board.class, boardId); board.setInternalTrello(this); for (TList list : board.getLists()) { list.setInternalTrello(this); } return board; } @Override public List<Action> getBoardActions(String boardId, Argument... args) { List<Action> actions = Arrays.asList(get(createUrl(GET_BOARD_ACTIONS).params(args).asString(), Action[].class, boardId)); for (Action action : actions) { action.setInternalTrello(this); } return actions; } @Override public List<Card> getBoardCards(String boardId, Argument... args) { List<Card> cards = Arrays.asList(get(createUrl(GET_BOARD_CARDS).params(args).asString(), Card[].class, boardId)); for (Card card : cards) { card.setInternalTrello(this); } return cards; } @Override public Card getBoardCard(String boardId, String cardId, Argument... args) { Card card = get(createUrl(GET_BOARD_CARD).params(args).asString(), Card.class, boardId, cardId); card.setInternalTrello(this); return card; } @Override public List<CheckList> getBoardChecklists(String boardId, Argument... args) { List<CheckList> checkLists = Arrays.asList(get(createUrl(GET_BOARD_CHECKLISTS).params(args).asString(), CheckList[].class, boardId)); for (CheckList checkList : checkLists) { checkList.setInternalTrello(this); } return checkLists; } @Override public List<Label> getBoardLabels(String boardId, Argument... args) { List<Label> labels = Arrays .asList(get(createUrl(GET_BOARD_LABELS).params(args).asString(), Label[].class, boardId)); for (Label label : labels) { label.setInternalTrello(this); } return labels; } @Override public List<TList> getBoardLists(String boardId, Argument... args) { List<TList> tLists = Arrays.asList(get(createUrl(GET_BOARD_LISTS).params(args).asString(), TList[].class, boardId)); for (TList list : tLists) { list.setInternalTrello(this); for (Card card : list.getCards()) { card.setInternalTrello(this); } } return tLists; } @Override public List<Member> getBoardMembers(String boardId, Argument... args) { List<Member> members = Arrays.asList(get(createUrl(GET_BOARD_MEMBERS).params(args).asString(), Member[].class, boardId)); for (Member member : members) { member.setInternalTrello(this); } return members; } @Override public List<Card> getBoardMemberCards(String boardId, String memberId, Argument... args) { List<Card> cards = Arrays.asList(get(createUrl(GET_BOARD_MEMBER_CARDS).params(args).asString(), Card[].class, boardId, memberId)); for (Card card : cards) { card.setInternalTrello(this); } return cards; } // FIXME Remove this method @Override @Deprecated public List<CardWithActions> getBoardMemberActivity(String boardId, String memberId, String actionFilter, Argument... args) { if (actionFilter == null) actionFilter = "all"; Argument[] argsAndFilter = Arrays.copyOf(args, args.length + 1); argsAndFilter[args.length] = new Argument("actions", actionFilter); List<CardWithActions> cards = Arrays.asList(get( createUrl(GET_BOARD_MEMBER_CARDS).params(argsAndFilter).asString(), CardWithActions[].class, boardId, memberId)); for (Card card : cards) { card.setInternalTrello(this); } return cards; } @Override public List<Member> getBoardMemberships(String boardId, Argument... args) { List<Member> members = Arrays.asList(get(createUrl(GET_BOARD_MEMBERSHIPS).params(args).asString(), Member[].class, boardId)); members.forEach(m -> m.setInternalTrello(this)); return members; } @Override public MyPrefs getBoardMyPrefs(String boardId) { MyPrefs myPrefs = get(createUrl(GET_BOARD_MYPREFS).asString(), MyPrefs.class, boardId); myPrefs.setInternalTrello(this); return myPrefs; } @Override public Organization getBoardOrganization(String boardId, Argument... args) { Organization organization = get(createUrl(GET_BOARD_ORGANIZATION).params(args).asString(), Organization.class, boardId); organization.setInternalTrello(this); return organization; } /* Action */ @Override public Action getAction(String actionId, Argument... args) { Action action = get(createUrl(GET_ACTION).params(args).asString(), Action.class, actionId); action.setInternalTrello(this); return action; } @Override public Board getActionBoard(String actionId, Argument... args) { Board board = get(createUrl(GET_ACTION_BOARD).params(args).asString(), Board.class, actionId); board.setInternalTrello(this); return board; } @Override public Card getActionCard(String actionId, Argument... args) { Card card = get(createUrl(GET_ACTION_CARD).params(args).asString(), Card.class, actionId); card.setInternalTrello(this); return card; } @Override public List<Entity> getActionEntities(String actionId) { List<Entity> entities = Arrays.asList(get(createUrl(GET_ACTION_ENTITIES).asString(), Entity[].class, actionId)); for (Entity entity : entities) { entity.setInternalTrello(this); } return entities; } @Override public TList getActionList(String actionId, Argument... args) { TList tList = get(createUrl(GET_ACTION_LIST).params(args).asString(), TList.class, actionId); tList.setInternalTrello(this); return tList; } @Override public Member getActionMember(String actionId, Argument... args) { Member member = get(createUrl(GET_ACTION_MEMBER).params(args).asString(), Member.class, actionId); member.setInternalTrello(this); return member; } @Override public Member getActionMemberCreator(String actionId, Argument... args) { Member member = get(createUrl(GET_ACTION_MEMBER_CREATOR).params(args).asString(), Member.class, actionId); member.setInternalTrello(this); return member; } @Override public Organization getActionOrganization(String actionId, Argument... args) { Organization organization = get(createUrl(GET_ACTION_ORGANIZATION).params(args).asString(), Organization.class, actionId); organization.setInternalTrello(this); return organization; } @Override public Card getCard(String cardId, Argument... args) { Card card = get(createUrl(GET_CARD).params(args).asString(), Card.class, cardId); card.setInternalTrello(this); return card; } @Override public List<Action> getCardActions(String cardId, Argument... args) { List<Action> actions = Arrays.asList(get(createUrl(GET_CARD_ACTIONS).params(args).asString(), Action[].class, cardId)); for (Action action : actions) { action.setInternalTrello(this); } return actions; } @Override public List<Attachment> getCardAttachments(String cardId, Argument... args) { List<Attachment> attachments = Arrays.asList(get(createUrl(GET_CARD_ATTACHMENTS).params(args).asString(), Attachment[].class, cardId)); for (Attachment attachment : attachments) { attachment.setInternalTrello(this); } return attachments; } @Override public Attachment getCardAttachment(String cardId, String attachmentId, Argument... args) { Attachment attachment = get(createUrl(GET_CARD_ATTACHMENT).params(args).asString(), Attachment.class, cardId, attachmentId); attachment.setInternalTrello(this); return attachment; } @Override public Board getCardBoard(String cardId, Argument... args) { Board board = get(createUrl(GET_CARD_BOARD).params(args).asString(), Board.class, cardId); board.setInternalTrello(this); return board; } @Override public List<CheckList> getCardChecklists(String cardId, Argument... args) { List<CheckList> checkLists = Arrays.asList(get(createUrl(GET_CARD_CHECKLIST).params(args).asString(), CheckList[].class, cardId)); for (CheckList checklist : checkLists) { checklist.setInternalTrello(this); } return checkLists; } /* Lists */ @Override public TList getList(String listId, Argument... args) { TList tList = get(createUrl(GET_LIST).params(args).asString(), TList.class, listId); tList.setInternalTrello(this); return tList; } @Override public List<Card> getListCards(String listId, Argument... args) { List<Card> cards = Arrays.asList(get(createUrl(GET_LIST_CARDS).params(args).asString(), Card[].class, listId)); for (Card card : cards) { card.setInternalTrello(this); } return cards; } /* Organizations */ @Override public List<Board> getOrganizationBoards(String organizationId, Argument... args) { List<Board> boards = Arrays.asList(get(createUrl(GET_ORGANIZATION_BOARD).params(args).asString(), Board[].class, organizationId)); for (Board board : boards) { board.setInternalTrello(this); } return boards; } @Override public List<Member> getOrganizationMembers(String organizationId, Argument... args) { List<Member> members = Arrays.asList(get(createUrl(GET_ORGANIZATION_MEMBER).params(args).asString(), Member[].class, organizationId)); for (Member member : members) { member.setInternalTrello(this); } return members; } /* CheckLists */ @Override public CheckList getCheckList(String checkListId, Argument... args) { CheckList checkList = get(createUrl(GET_CHECK_LIST).params(args).asString(), CheckList.class, checkListId); checkList.setInternalTrello(this); return checkList; } @Override public CheckList createCheckList(String cardId, CheckList checkList) { checkList.setIdCard(cardId); CheckList createdCheckList = postForObject(createUrl(CREATE_CHECKLIST).asString(), checkList, CheckList.class); createdCheckList.setInternalTrello(this); return createdCheckList; } @Override public void createCheckItem(String checkListId, CheckItem checkItem) { postForLocation(createUrl(ADD_CHECKITEMS_TO_CHECKLIST).asString(), checkItem, checkListId); } /* Others */ @Override public Card createCard(String listId, Card card) { card.setIdList(listId); try { Card createdCard = postForObject(createUrl(CREATE_CARD).asString(), card, Card.class); createdCard.setInternalTrello(this); return createdCard; } catch (TrelloBadRequestException e) { throw decodeException(card, e); } } @Override public Card updateCard(Card card) { try { Card put = put(createUrl(UPDATE_CARD).asString(), card, Card.class, card.getId()); put.setInternalTrello(this); return put; } catch (TrelloBadRequestException e) { throw decodeException(card, e); } } private static TrelloBadRequestException decodeException(Card card, TrelloBadRequestException e) { if (e.getMessage().contains("invalid value for idList")) { return new ListNotFoundException(card.getIdList()); } if (e instanceof NotFoundException) { return new NotFoundException("Card with id " + card.getId() + " is not found. It may have been deleted in Trello"); } return e; } @Override // FIXME Remove this method @Deprecated public Member getBasicMemberInformation(String username) { Member member = get(createUrl(GET_MEMBER).params(new Argument("fields", "username,fullName")).asString(), Member.class, username); member.setInternalTrello(this); return member; } @Override public Member getMemberInformation(String username) { Member member = get(createUrl(GET_MEMBER).asString(), Member.class, username); member.setInternalTrello(this); return member; } @Override public List<Board> getMemberBoards(String userId, Argument... args) { List<Board> boards = Arrays.asList(get(createUrl(GET_MEMBER_BOARDS).params(args).asString(), Board[].class, userId)); for (Board board : boards) { board.setInternalTrello(this); } return boards; } @Override public List<Action> getMemberActions(String userId, Argument... args) { List<Action> actions = Arrays.asList(get(createUrl(GET_MEMBER_ACTIONS).params(args).asString(), Action[].class, userId)); for (Action action : actions) { action.setInternalTrello(this); } return actions; } @Override public void addLabelsToCard(String idCard, String[] labels) { for (String labelName : labels) { Label label = new Label(); label.setName(labelName); postForObject(createUrl(ADD_LABEL_TO_CARD).asString(), label, Label.class, idCard); } } @Override public void addCommentToCard(String idCard, String comment) { postForObject(createUrl(ADD_COMMENT_TO_CARD).asString(), new Comment(comment), Comment.class, idCard); } @Override public void addAttachmentToCard(String idCard, File file) { postFileForObject(createUrl(ADD_ATTACHMENT_TO_CARD).asString(), file, Attachment.class, idCard); } @Override public void addUrlAttachmentToCard(String idCard, String url) { postForObject(createUrl(ADD_ATTACHMENT_TO_CARD).asString(), new Attachment(url), Attachment.class, idCard); } /* internal methods */ private <T> T postFileForObject(String url, File file, Class<T> objectClass, String... params) { logger.debug("PostFileForObject request on Trello API at url {} for class {} with params {}", url, objectClass.getCanonicalName(), params); if (!(httpClient instanceof ApacheHttpClient)) { throw new IllegalStateException("postForFile is implemented only on ApacheHttpClient."); } return ((ApacheHttpClient)httpClient).postFileForObject(url, file, objectClass, enrichParams(params)); } private <T> T postForObject(String url, T object, Class<T> objectClass, String... params) { logger.debug("PostForObject request on Trello API at url {} for class {} with params {}", url, objectClass.getCanonicalName(), params); return httpClient.postForObject(url, object, objectClass, enrichParams(params)); } private void postForLocation(String url, Object object, String... params) { logger.debug("PostForLocation request on Trello API at url {} for class {} with params {}", url, object.getClass().getCanonicalName(), params); httpClient.postForLocation(url, object, enrichParams(params)); } private <T> T get(String url, Class<T> objectClass, String... params) { logger.debug("Get request on Trello API at url {} for class {} with params {}", url, objectClass.getCanonicalName(), params); return httpClient.get(url, objectClass, enrichParams(params)); } private <T> T put(String url, T object, Class<T> objectClass, String... params) { logger.debug("Put request on Trello API at url {} for class {} with params {}", url, object.getClass().getCanonicalName(), params); return httpClient.putForObject(url, object, objectClass, enrichParams(params)); } private String[] enrichParams(String[] params) { List<String> paramList = new ArrayList<>(Arrays.asList(params)); paramList.add(applicationKey); paramList.add(accessToken); return paramList.toArray(new String[paramList.size()]); } }
package com.kiuwan.client.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @XmlRootElement @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class AnalysisBean { /** * Analysis status that indicates that the analysis is queued waiting for some analysis slot. */ public static final String INQUEUE_STATUS = "INQUEUE"; /** * Analysis status that indicates that the analysis has failed. */ public static final String FAIL_STATUS = "FAIL"; /** * Analysis status that indicates that the analysis has been completed successfully. */ public static final String SUCCESS_STATUS = "SUCCESS"; /** * Analysis status that indicates that the analysis is running. */ public static final String RUNNING_STATUS = "RUNNING"; private String code; private String label; private String creationDate; private String qualityModel; private String encoding; private String invoker; private String status; private String errorCode; private List<UnparsedFileBean> unparsedFiles = new ArrayList<UnparsedFileBean>(); /** * @return the code */ public String getCode() { return code; } /** * @param code the code to set */ public void setCode(String code) { this.code = code; } /** * @return the label */ public String getLabel() { return label; } /** * @param label the label to set */ public void setLabel(String label) { this.label = label; } /** * @return the creationDate */ public String getCreationDate() { return creationDate; } /** * @param creationDate the creationDate to set */ public void setCreationDate(String creationDate) { this.creationDate = creationDate; } /** * @return the qualityModel */ public String getQualityModel() { return qualityModel; } /** * @param qualityModel the qualityModel to set */ public void setQualityModel(String qualityModel) { this.qualityModel = qualityModel; } /** * @return the encoding */ public String getEncoding() { return encoding; } /** * @param encoding the encoding to set */ public void setEncoding(String encoding) { this.encoding = encoding; } /** * @return the invoker */ public String getInvoker() { return invoker; } /** * @param invoker the invoker to set */ public void setInvoker(String invoker) { this.invoker = invoker; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the errorCode */ public String getErrorCode() { return errorCode; } /** * @param errorCode the errorCode to set */ public void setErrorCode(String errorCode) { this.errorCode = errorCode; } /** * @return the unparsedFiles */ public List<UnparsedFileBean> getUnparsedFiles() { return unparsedFiles; } /** * @param unparsedFiles the unparsedFiles to set */ public void setUnparsedFiles(List<UnparsedFileBean> unparsedFiles) { this.unparsedFiles = unparsedFiles; } @Override public String toString() { String unparsedFilesString = ""; for (UnparsedFileBean unparsedFileBean : unparsedFiles) { String file = unparsedFileBean.getFile(); String cause = unparsedFileBean.getCause(); unparsedFilesString = unparsedFilesString + "{file:"+file+", cause:"+cause+"}"; } return "Analysis [code=" + code + ", label=" + label + ", " + "creationDate=" + creationDate + ", qualityModel=" + qualityModel + ", encoding=" + encoding + ", invoker=" + invoker + ", status=" + status + ", errorCode=" + errorCode + ", unparsedFiles=" + "["+unparsedFilesString+"]]"; } }
package com.lagodiuk.decisiontree.demo; import com.lagodiuk.decisiontree.*; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; public class Demo5 { public static void main(String[] args) { DecisionTreeBuilder builder = DecisionTree .createBuilder() .setTrainingSet( makeTrainingSet() ) .setDefaultPredicates( Predicate.GTE, Predicate.LTE ) .setMinimalNumberOfItems( 7 ); RandomForest forest = RandomForest.create(builder, 10); JFrame f1 = new JFrame(); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f1.setSize(300, 300); f1.setLocationRelativeTo(null); JPanel p = new JPanel(); f1.add(p); f1.setVisible(true); BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); for (int x = 0; x < 200; x++) { for (int y = 0; y < 200; y++) { Item item = makeEmptyItem((x - 100) / 5, (y - 100) / 5); Map<Object, Integer> result = forest.classify(item); int red = 0; int green = 0; for (Object colour : result.keySet()) { if ("red".equals(colour)) { red = result.get(colour); } else if ("green".equals(colour)) { green = result.get(colour); } } g.setColor(new Color(((float) red) / (red + green), ((float) green) / (red + green), 0)); g.drawOval(x, y, 2, 2); } } while( true ) { p.getGraphics().drawImage(bi, 0, 0, null); } } private static List<Item> makeTrainingSet() { Random random = new Random(); List<Item> items = new LinkedList<Item>(); for (double i = 0; i <= 700; i++) { items.add(makeItem((random.nextDouble() - random.nextDouble()) * 14, (random.nextDouble() - random.nextDouble()) * 14)); } return items; } private static Item makeItem(double x, double y) { Item item = new Item(); if ((((x * x) + (y * y)) <= (10 * 10)) && (Math.random() < 0.9)) { item.setCategory("red"); if ((((x * x) + (y * y)) <= (5 * 5)) && (Math.random() < 0.8)) { item.setCategory("green"); } } else { item.setCategory("green"); } item.setAttribute("x", x); item.setAttribute("y", y); return item; } private static Item makeEmptyItem(double x, double y) { Item item = new Item(); item.setAttribute("x", x); item.setAttribute("y", y); return item; } }
package com.lothrazar.item; import java.util.List; import com.google.common.collect.Sets; import com.lothrazar.event.HandlerWand; import com.lothrazar.samscontent.ItemRegistry; import com.lothrazar.samscontent.ModLoader; import com.lothrazar.util.Reference; import com.lothrazar.util.SamsRegistry; import com.lothrazar.util.SamsUtilities; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import net.minecraft.block.BlockChest; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.passive.EntityBat; import net.minecraft.entity.passive.EntityChicken; import net.minecraft.entity.passive.EntityCow; import net.minecraft.entity.passive.EntityMooshroom; import net.minecraft.entity.passive.EntityPig; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerInteractEvent; public class ItemWandTransform extends ItemTool { private static int DURABILITY = 80; public static boolean drainsHunger = false; public static boolean drainsDurability = true; public ItemWandTransform( ) { super(1.0F,Item.ToolMaterial.WOOD, Sets.newHashSet()); this.setMaxDamage(DURABILITY); this.setMaxStackSize(1); this.setCreativeTab(ModLoader.tabSamsContent); } @Override public boolean hasEffect(ItemStack par1ItemStack) { return true; //give it shimmer } public static void onInit() { // if(!ModLoader.settings.masterWand){return;} //TODO: config/recipe ItemRegistry.wandTransform = new ItemWandTransform(); SamsRegistry.registerItem(ItemRegistry.wandTransform, "wand_transform"); /* GameRegistry.addRecipe(new ItemStack(itemWand) ,"bdb" ," b " ," b " , 'd', Blocks.emerald_block , 'b', Items.blaze_rod ); if(ModLoader.settings.uncraftGeneral) GameRegistry.addSmelting(itemWand, new ItemStack(Blocks.emerald_block,1,0),0); //recycling */ } private static int INVALID = -1; public static void transformBlock(EntityPlayer player, World world, ItemStack heldWand, BlockPos pos) { IBlockState blockState = player.worldObj.getBlockState(pos); Block block = blockState.getBlock(); int metaCurrent, metaNew = INVALID; IBlockState blockStateNew = null; if(block == Blocks.red_mushroom_block) { metaCurrent = Blocks.red_mushroom_block.getMetaFromState(blockState); //from wiki we know that [11-13] are unused //meta 14 is only vanilla used one //OLD one was meta 0, all pores // http://minecraft.gamepedia.com/Data_values#Brown_and_red_mushroom_blocks if(0 <= metaCurrent && metaCurrent <= 9) metaNew = metaCurrent + 1; else if(metaCurrent == 10) metaNew = 14; else if(metaCurrent == 14) metaNew = 15; else if(metaCurrent == 15) metaNew = 0; if(metaNew > INVALID) blockStateNew = Blocks.red_mushroom_block.getStateFromMeta(metaNew); } else if(block == Blocks.stonebrick) { metaCurrent = Blocks.stonebrick.getMetaFromState(blockState); if(metaCurrent == 0)//0 is regular, 3 is chiseled metaNew = 3; else if(metaCurrent == 3) metaNew = 0; //Not doing mossy or cracked here is deliberate, it costs vines or smelting time to make those if(metaNew > INVALID) blockStateNew = Blocks.stonebrick.getStateFromMeta(metaNew); } else if(block == Blocks.stone) { metaCurrent = Blocks.stone.getMetaFromState(blockState); //skip 0 which is regular stone //granite regular/polish if(metaCurrent == 1) metaNew = 2; else if(metaCurrent == 2) metaNew = 1; //diorite regular/polish if(metaCurrent == 3) metaNew = 4; else if(metaCurrent == 4) metaNew = 3; //andesite regular/polish if(metaCurrent == 5) metaNew = 6; else if(metaCurrent == 6) metaNew = 5; if(metaNew > INVALID) blockStateNew = Blocks.stone.getStateFromMeta(metaNew); } else if(block == Blocks.brown_mushroom_block) { metaCurrent = Blocks.brown_mushroom_block.getMetaFromState(blockState); if(0 <= metaCurrent && metaCurrent <= 9) metaNew = metaCurrent+1; else if(metaCurrent == 10) metaNew = 14; else if(metaCurrent == 14) metaNew = 15; else if(metaCurrent == 15) metaNew = 0; if(metaNew > INVALID) blockStateNew = Blocks.brown_mushroom_block.getStateFromMeta(metaNew); } else if(block == Blocks.double_stone_slab) { metaCurrent = Blocks.double_stone_slab.getMetaFromState(blockState); if(metaCurrent == 0)//smoothstone slabs metaNew = 8; else if(metaCurrent == 8) metaNew = 0; if(metaCurrent == 1)//samdstpme slabs metaNew = 9; else if(metaCurrent == 9) metaNew = 1; if(metaNew > INVALID) blockStateNew = Blocks.double_stone_slab.getStateFromMeta(metaNew); } else if(block == Blocks.double_stone_slab2) { metaCurrent = Blocks.double_stone_slab2.getMetaFromState(blockState); if(metaCurrent == 0)//RED sandstone slabs metaNew = 8; else if(metaCurrent == 8) metaNew = 0; if(metaNew > INVALID) blockStateNew = Blocks.double_stone_slab2.getStateFromMeta(metaNew); } else if(block == Blocks.log2) { metaCurrent = Blocks.log2.getMetaFromState(blockState); int acaciaVert = 0; int darkVert=1; int acaciaEast=4; int darkEast=5; int acaciaNorth=8; int darkNorth=9; int acaciaMagic=12; int darkMagic=13; if(metaCurrent == acaciaVert) metaNew = acaciaEast; else if(metaCurrent == acaciaEast) metaNew = acaciaNorth; else if(metaCurrent == acaciaNorth) metaNew = acaciaMagic; else if(metaCurrent == acaciaMagic) metaNew = acaciaVert; if(metaCurrent == darkVert) metaNew = darkEast; else if(metaCurrent == darkEast) metaNew = darkNorth; else if(metaCurrent == darkNorth) metaNew = darkMagic; else if(metaCurrent == darkMagic) metaNew = darkVert; if(metaNew > INVALID) blockStateNew = Blocks.log2.getStateFromMeta(metaNew); } else if(block == Blocks.log) { metaCurrent = Blocks.log.getMetaFromState(blockState); int oakVert = 0; int spruceVert=1; int birchVert=2; int jungleVert=3; int oakEast=4; int spruceEast=5; int birchEast=6; int jungleEast=7; int oakNorth=8; int spruceNorth=9; int birchNorth=10; int jungleNorth=11; int oakMagic=12; int spruceMagic=13; int birchMagic=14; int jungleMagic=15;//http://minecraft.gamepedia.com/Data_values#Wood if(metaCurrent == oakVert) metaNew = oakEast; else if(metaCurrent == oakEast) metaNew = oakNorth; else if(metaCurrent == oakNorth) metaNew = oakMagic; else if(metaCurrent == oakMagic) metaNew = oakVert; else if(metaCurrent == birchVert) metaNew = birchEast; else if(metaCurrent == birchEast) metaNew = birchNorth; else if(metaCurrent == birchNorth) metaNew = birchMagic; else if(metaCurrent == birchMagic) metaNew = birchVert; else if(metaCurrent == spruceVert) metaNew = spruceEast; else if(metaCurrent == spruceEast) metaNew = spruceNorth; else if(metaCurrent == spruceNorth) metaNew = spruceMagic; else if(metaCurrent == spruceMagic) metaNew = spruceVert; else if(metaCurrent == jungleVert) metaNew = jungleEast; else if(metaCurrent == jungleEast) metaNew = jungleNorth; else if(metaCurrent == jungleNorth) metaNew = jungleMagic; else if(metaCurrent == jungleMagic) metaNew = jungleVert; if(metaNew > INVALID) { blockStateNew = Blocks.log.getStateFromMeta(metaNew); } } else if(block == Blocks.stone_slab) { metaCurrent = Blocks.stone_slab.getMetaFromState(blockState); if(metaCurrent <= 7) metaNew = metaCurrent + 8; else metaNew = metaCurrent - 8; if(metaNew > INVALID) { blockStateNew = Blocks.stone_slab.getStateFromMeta(metaNew); } } else if(block == Blocks.stone_slab2) { metaCurrent = Blocks.stone_slab2.getMetaFromState(blockState); if(metaCurrent <= 7) metaNew = metaCurrent + 8; else metaNew = metaCurrent - 8; if(metaNew > INVALID) { blockStateNew = Blocks.stone_slab2.getStateFromMeta(metaNew); } } else if(block == Blocks.wooden_slab) { metaCurrent = Blocks.wooden_slab.getMetaFromState(blockState); if(metaCurrent <= 7) metaNew = metaCurrent + 8; else metaNew = metaCurrent - 8; if(metaNew > INVALID) { blockStateNew = Blocks.wooden_slab.getStateFromMeta(metaNew); } } else if(block == Blocks.sandstone) { metaCurrent = Blocks.sandstone.getMetaFromState(blockState); if(metaCurrent == 2) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.sandstone.getStateFromMeta(metaNew); } } else if(block == Blocks.red_sandstone) { metaCurrent = Blocks.red_sandstone.getMetaFromState(blockState); if(metaCurrent == 2) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.red_sandstone.getStateFromMeta(metaNew); } } else if(block == Blocks.sandstone_stairs) { metaCurrent = Blocks.sandstone_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.sandstone_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.red_sandstone_stairs) { metaCurrent = Blocks.red_sandstone_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.red_sandstone_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.stone_stairs) { metaCurrent = Blocks.stone_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.stone_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.stone_brick_stairs) { metaCurrent = Blocks.stone_brick_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.stone_brick_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.quartz_stairs) { metaCurrent = Blocks.quartz_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.quartz_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.brick_stairs) { metaCurrent = Blocks.brick_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.brick_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.spruce_stairs) { metaCurrent = Blocks.spruce_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.spruce_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.birch_stairs) { metaCurrent = Blocks.birch_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.birch_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.oak_stairs) { metaCurrent = Blocks.oak_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.oak_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.jungle_stairs) { metaCurrent = Blocks.jungle_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.jungle_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.acacia_stairs) { metaCurrent = Blocks.acacia_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.acacia_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.dark_oak_stairs) { metaCurrent = Blocks.dark_oak_stairs.getMetaFromState(blockState); if(metaCurrent == 8) metaNew = 0; else metaNew = metaCurrent + 1; if(metaNew > INVALID) { blockStateNew = Blocks.dark_oak_stairs.getStateFromMeta(metaNew); } } else if(block == Blocks.quartz_block) { metaCurrent = Blocks.quartz_block.getMetaFromState(blockState); if(metaCurrent == 4) metaNew = 0; else metaNew = metaCurrent + 1; //rotate pillars, or change to pillared/smooth if(metaNew > INVALID) { blockStateNew = Blocks.quartz_block.getStateFromMeta(metaNew); } } else if(block == Blocks.pumpkin) { metaCurrent = Blocks.pumpkin.getMetaFromState(blockState); if(metaCurrent == 4) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.pumpkin.getStateFromMeta(metaNew); } } else if(block == Blocks.lit_pumpkin) { metaCurrent = Blocks.lit_pumpkin.getMetaFromState(blockState); if(metaCurrent == 4) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.lit_pumpkin.getStateFromMeta(metaNew); } } else if(block == Blocks.rail) { metaCurrent = Blocks.rail.getMetaFromState(blockState); /*RAILS: * 0 Straight rail connecting to the north and south. 1 Straight rail connecting to the east and west. 2 Sloped rail ascending to the east. 3 Sloped rail ascending to the west. 4 Sloped rail ascending to the north. 5 Sloped rail ascending to the south. 6 Curved rail connecting to the south and east. 7 Curved rail connecting to the south and west. 8 Curved rail connecting to the north and west. 9 Curved rail connecting to the north and east.*/ if(metaCurrent == 9) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.rail.getStateFromMeta(metaNew); } } else if(block == Blocks.dropper) { metaCurrent = Blocks.dropper.getMetaFromState(blockState); if(metaCurrent == 5) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.dropper.getStateFromMeta(metaNew); } } else if(block == Blocks.dispenser) { metaCurrent = Blocks.dispenser.getMetaFromState(blockState); if(metaCurrent == 5) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.dispenser.getStateFromMeta(metaNew); } } else if(block == Blocks.hopper) { metaCurrent = Blocks.hopper.getMetaFromState(blockState); if(metaCurrent == 5) metaNew = 0; else if(metaCurrent == 0) //1 is unused (cant point Up) metaNew = 2; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.hopper.getStateFromMeta(metaNew); } } else if(block == Blocks.furnace) { metaCurrent = Blocks.furnace.getMetaFromState(blockState); if(metaCurrent == 5) //0,1 are down/up, but only 4 directions here metaNew = 2; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.furnace.getStateFromMeta(metaNew); } } else if(block == Blocks.piston) { metaCurrent = Blocks.piston.getMetaFromState(blockState); if(metaCurrent == 5) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.piston.getStateFromMeta(metaNew); } } else if(block == Blocks.sticky_piston) { metaCurrent = Blocks.sticky_piston.getMetaFromState(blockState); if(metaCurrent == 5) metaNew = 0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.sticky_piston.getStateFromMeta(metaNew); } } else if(block == Blocks.wall_sign) { metaCurrent = Blocks.wall_sign.getMetaFromState(blockState); if(metaCurrent == 5) //0,1 are down/up, but only 4 directions here metaNew = 2; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.wall_sign.getStateFromMeta(metaNew); } } else if(block == Blocks.standing_sign) { metaCurrent = Blocks.standing_sign.getMetaFromState(blockState); if(metaCurrent == 15) metaNew =0; else metaNew = metaCurrent + 1; //rotate if(metaNew > INVALID) { blockStateNew = Blocks.standing_sign.getStateFromMeta(metaNew); } } if(blockStateNew != null) { if(world.isRemote == true) { SamsUtilities.spawnParticle(world, EnumParticleTypes.CRIT_MAGIC, pos); SamsUtilities.spawnParticle(world, EnumParticleTypes.CRIT_MAGIC, player.getPosition()); player.swingItem(); } else { //server side stuff SamsUtilities.playSoundAt(player, "random.wood_click"); player.worldObj.setBlockState(pos,blockStateNew); if(drainsHunger) { SamsUtilities.drainHunger(player); } SamsUtilities.damageOrBreakHeld(player); } } } /* @Override public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par4) { list.add("For use only on"); list.add("Mushroom blocks"); list.add("Double Slabs"); } */ }
package com.netply.botchan.web.model; public class Message { private String id; private String message; private String sender; private boolean isDirect = false; public Message() { } public Message(String id, String message) { this(id, message, null); } public Message(String id, String message, String sender) { this(id, message, sender, false); } public Message(String id, String message, String sender, boolean isDirect) { this.id = id; this.message = message; this.sender = sender; this.isDirect = isDirect; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getMessage() { return message; } public void setSender(String sender) { this.sender = sender; } public String getSender() { return sender; } public void setIsDirect(boolean isDirect) { this.isDirect = isDirect; } public boolean getIsDirect() { return isDirect; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Message message1 = (Message) o; if (isDirect != message1.isDirect) return false; if (id != null ? !id.equals(message1.id) : message1.id != null) return false; if (message != null ? !message.equals(message1.message) : message1.message != null) return false; return sender != null ? sender.equals(message1.sender) : message1.sender == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (sender != null ? sender.hashCode() : 0); result = 31 * result + (isDirect ? 1 : 0); return result; } @Override public String toString() { return "Message{" + "id='" + id + '\'' + ", message='" + message + '\'' + ", sender='" + sender + '\'' + ", isDirect=" + isDirect + '}'; } }
package com.pump.showcase; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.TexturePaint; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JProgressBar; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JSpinner.DefaultEditor; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.pump.geom.Spiral2D; import com.pump.geom.StarPolygon; import com.pump.image.shadow.ARGBPixels; import com.pump.image.shadow.BoxShadowRenderer; import com.pump.image.shadow.DoubleBoxShadowRenderer; import com.pump.image.shadow.GaussianKernel; import com.pump.image.shadow.GaussianShadowRenderer; import com.pump.image.shadow.ShadowAttributes; import com.pump.image.shadow.ShadowRenderer; import com.pump.inspector.Inspector; import com.pump.showcase.Profiler.ProfileResults; import com.pump.showcase.ShadowRendererDemo.OriginalGaussianShadowRenderer; import com.pump.showcase.chart.LineChartRenderer; import com.pump.swing.DialogFooter; import com.pump.swing.DialogFooter.EscapeKeyBehavior; import com.pump.swing.JColorWell; import com.pump.swing.JFancyBox; import com.pump.swing.QDialog; public class ShadowRendererDemo extends ShowcaseExampleDemo { /** * For testing and comparison purposes: this is the original unoptimized * Gaussian shadow renderer. * */ public static class OriginalGaussianShadowRenderer implements ShadowRenderer { @Override public ARGBPixels createShadow(ARGBPixels src, ARGBPixels dst, float kernelRadius, Color shadowColor) { GaussianKernel kernel = getKernel(kernelRadius); int k = kernel.getKernelRadius(); int shadowSize = k * 2; int srcWidth = src.getWidth(); int srcHeight = src.getHeight(); int dstWidth = srcWidth + shadowSize; int dstHeight = srcHeight + shadowSize; if (dst == null) dst = new ARGBPixels(dstWidth, dstHeight); if (dst.getWidth() != dstWidth) throw new IllegalArgumentException( dst.getWidth() + " != " + dstWidth); if (dst.getHeight() != dstHeight) throw new IllegalArgumentException( dst.getWidth() + " != " + dstWidth); int[] dstBuffer = dst.getPixels(); int[] srcBuffer = src.getPixels(); int[] opacityLookup = new int[256]; { int rgb = shadowColor.getRGB() & 0xffffff; int alpha = shadowColor.getAlpha(); for (int a = 0; a < opacityLookup.length; a++) { int newAlpha = (int) (a * alpha / 255); opacityLookup[a] = (newAlpha << 24) + rgb; } } int x1 = k; int x2 = k + srcWidth; int[] kernelArray = kernel.getArray(); int kernelSum = kernel.getArraySum(); // vertical pass: for (int dstX = x1; dstX < x2; dstX++) { int srcX = dstX - k; for (int dstY = 0; dstY < dstHeight; dstY++) { int srcY = dstY - k; int g = srcY - k; int w = 0; for (int j = 0; j < kernelArray.length; j++) { int kernelY = g + j; if (kernelY >= 0 && kernelY < srcHeight) { int argb = srcBuffer[srcX + kernelY * srcWidth]; int alpha = argb >>> 24; w += alpha * kernelArray[j]; } } w = w / kernelSum; dstBuffer[dstY * dstWidth + dstX] = w; } } // horizontal pass: int[] row = new int[dstWidth]; for (int dstY = 0; dstY < dstHeight; dstY++) { System.arraycopy(dstBuffer, dstY * dstWidth, row, 0, row.length); for (int dstX = 0; dstX < dstWidth; dstX++) { int w = 0; for (int j = 0; j < kernelArray.length; j++) { int kernelX = dstX - k + j; if (kernelX >= 0 && kernelX < dstWidth) { w += row[kernelX] * kernelArray[j]; } } w = w / kernelSum; dstBuffer[dstY * dstWidth + dstX] = opacityLookup[w]; } } return dst; } @Override public GaussianKernel getKernel(float kernelRadius) { return new GaussianKernel(kernelRadius, false); } } public static BufferedImage createTestImage() { BufferedImage bi = new BufferedImage(300, 100, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.white); g.setStroke(new BasicStroke(4)); g.draw(new Ellipse2D.Float(-10, -10, 20, 20)); g.draw(new Ellipse2D.Float(bi.getWidth() - 10, bi.getHeight() - 10, 20, 20)); g.draw(new Ellipse2D.Float(bi.getWidth() - 10, -10, 20, 20)); g.draw(new Ellipse2D.Float(-10, bi.getHeight() - 10, 20, 20)); StarPolygon star = new StarPolygon(40); star.setCenter(50, 50); g.setColor(new Color(0x1BE7FF)); g.fill(star); BufferedImage textureBI = new BufferedImage(20, 60, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = textureBI.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); for (int z = 0; z < 500; z++) { g2.setStroke(new BasicStroke(8)); g2.setColor(new Color(0xFF5714)); g2.drawLine(-100 + z * 20, 100, 100 + z * 20, -100); g2.setStroke(new BasicStroke(10)); g2.setColor(new Color(0x6EEB83)); g2.drawLine(200 - z * 20, 100, 0 - z * 20, -100); } g2.dispose(); Rectangle r = new Rectangle(0, 0, textureBI.getWidth(), textureBI.getHeight()); g.setPaint(new TexturePaint(textureBI, r)); Shape roundRect = new RoundRectangle2D.Float(110, 10, 80, 80, 40, 40); g.fill(roundRect); Spiral2D spiral = new Spiral2D(250, 50, 20, 2, 0, 0, true); g.setStroke(new BasicStroke(10)); g.setColor(new Color(0xE8AA14)); g.draw(spiral); return bi; } private static final long serialVersionUID = 1L; /** * The maximum dx & dy offset for the shadow */ private final static int MAX_OFFSET = 25; JComboBox<String> rendererComboBox = new JComboBox<>(); JSpinner kernelSizeSpinner = new JSpinner( new SpinnerNumberModel(5f, 0f, 25f, .5f)); JSlider opacitySlider = new ShowcaseSlider(1, 100, 50); JSlider xOffsetSlider = new ShowcaseSlider(-MAX_OFFSET, MAX_OFFSET, 10); JSlider yOffsetSlider = new ShowcaseSlider(-MAX_OFFSET, MAX_OFFSET, 10); JColorWell colorWell = new JColorWell(Color.black); BufferedImage srcImage; ActionListener refreshActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { refreshExample(); } }; ChangeListener refreshChangeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { refreshExample(); } }; public ShadowRendererDemo() { super(); Inspector inspector = new Inspector(configurationPanel); inspector.addRow(new JLabel("Renderer:"), rendererComboBox); inspector.addRow(new JLabel("Kernel Size:"), kernelSizeSpinner); inspector.addRow(new JLabel("X:"), xOffsetSlider); inspector.addRow(new JLabel("Y:"), yOffsetSlider); inspector.addRow(new JLabel("Color:"), colorWell); inspector.addRow(new JLabel("Opacity:"), opacitySlider); rendererComboBox.addItem("Box"); rendererComboBox.addItem("Double Box"); rendererComboBox.addItem("Gaussian"); // use Double Box as default: rendererComboBox.setSelectedIndex(1); addSliderPopover(opacitySlider, "%"); addSliderPopover(xOffsetSlider, " pixels"); addSliderPopover(yOffsetSlider, " pixels"); rendererComboBox.addActionListener(refreshActionListener); kernelSizeSpinner.addChangeListener(refreshChangeListener); opacitySlider.addChangeListener(refreshChangeListener); xOffsetSlider.addChangeListener(refreshChangeListener); yOffsetSlider.addChangeListener(refreshChangeListener); colorWell.getColorSelectionModel() .addChangeListener(refreshChangeListener); ((DefaultEditor) kernelSizeSpinner.getEditor()).getTextField() .setColumns(4); refreshExample(); } @Override protected JComponent getComponentBelowExamplePanel() { JButton profileButton = new JButton("Profile Performance"); profileButton.addActionListener(new ActionListener() { Profiler profiler; @Override public void actionPerformed(ActionEvent e) { JFrame frame = (JFrame) SwingUtilities .getWindowAncestor(ShadowRendererDemo.this); if (profiler == null) { profiler = new Profiler(ShadowRendererDemo.this); } ProfileResults results = profiler.getResults(); if (results != null) { LineChartRenderer renderer = new LineChartRenderer( profiler.results.data); BufferedImage bi = renderer.render(new Dimension(600, 400)); JLabel content = new JLabel(new ImageIcon(bi)); JFancyBox box = new JFancyBox(frame, content); box.setVisible(true); } else { profiler = null; } } }); return profileButton; } protected void refreshExample() { examplePanel.removeAll(); examplePanel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.insets = new Insets(3, 3, 3, 3); examplePanel.add(new JLabel(new ImageIcon(createShadowedImage())), c); c.gridy++; c.anchor = GridBagConstraints.WEST; examplePanel.revalidate(); examplePanel.repaint(); } private BufferedImage createShadowedImage() { if (srcImage == null) srcImage = createTestImage(); Dimension size = new Dimension(srcImage.getWidth(), srcImage.getHeight()); SpinnerNumberModel model = (SpinnerNumberModel) kernelSizeSpinner .getModel(); Number max = (Number) model.getMaximum(); size.width += 2 * max.intValue() + 2 * MAX_OFFSET; size.height += 2 * max.intValue() + 2 * MAX_OFFSET; BufferedImage returnValue = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); ShadowRenderer renderer; if (rendererComboBox.getSelectedIndex() == 0) { renderer = new BoxShadowRenderer(); } else if (rendererComboBox.getSelectedIndex() == 1) { renderer = new DoubleBoxShadowRenderer(); } else { renderer = new GaussianShadowRenderer(); } float opacity = (float) (opacitySlider.getValue()) / 100f; Color color = colorWell.getColorSelectionModel().getSelectedColor(); color = new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (255 * opacity)); Number k1 = (Number) kernelSizeSpinner.getValue(); int dx = xOffsetSlider.getValue(); int dy = yOffsetSlider.getValue(); ShadowAttributes attr = new ShadowAttributes(dx, dy, k1.floatValue(), color); Graphics2D g = returnValue.createGraphics(); renderer.paint(g, srcImage, returnValue.getWidth() / 2 - srcImage.getWidth() / 2, returnValue.getHeight() / 2 - srcImage.getHeight() / 2, attr); g.dispose(); return returnValue; } @Override public String getTitle() { return "Shadow Demo"; } @Override public String getSummary() { return "This demonstrates a couple of options for rendering shadows."; } @Override public URL getHelpURL() { // TODO Auto-generated method stub return null; } @Override public String[] getKeywords() { return new String[] { "shadow", "gaussian", "blur", "image" }; } @Override public Class<?>[] getClasses() { return new Class[] { ShadowRenderer.class, ShadowAttributes.class, BoxShadowRenderer.class, GaussianShadowRenderer.class }; } } /** * This compares the performance of different ShadowRenderers as the kernel * radius increases. * <p> * This class includes the UI and the comparison logic. */ class Profiler { static class ProfileResults { Map<String, SortedMap<Double, Double>> data = new TreeMap<>(); public void store(ShadowRenderer renderer, float kernelSize, long time) { SortedMap<Double, Double> m = data .get(renderer.getClass().getSimpleName()); if (m == null) { m = new TreeMap<>(); data.put(renderer.getClass().getSimpleName(), m); } m.put((double) kernelSize, (double) time); } public void printTable() { StringBuilder sb = new StringBuilder(); sb.append("Kernel\t"); for (String name : data.keySet()) { sb.append(name); sb.append("\t"); } System.out.println(sb.toString().trim()); SortedSet<Double> allKeys = new TreeSet<>(); for (SortedMap<Double, Double> m : data.values()) { allKeys.addAll(m.keySet()); } for (Double key : allKeys) { sb.delete(0, sb.length()); sb.append(key.toString()); sb.append("\t"); for (String name : data.keySet()) { sb.append(data.get(name).get(key)); sb.append("\t"); } System.out.println(sb.toString().trim()); } } } static class UpdateProgressBar implements Runnable { JProgressBar progressBar; int min, max, value; UpdateProgressBar(JProgressBar progressBar, int min, int max, int value) { this.progressBar = progressBar; this.min = min; this.max = max; this.value = value; } @Override public void run() { progressBar.getModel().setRangeProperties(value, 1, min, max, false); progressBar.setIndeterminate(false); } } static class RunSample implements Runnable { ShadowRenderer renderer; ShadowAttributes attr; ARGBPixels srcPixels, dstPixels; ProfileResults profileResults; public RunSample(ProfileResults profileResults, ShadowRenderer renderer, ShadowAttributes attr, ARGBPixels srcPixels, ARGBPixels dstPixels) { this.renderer = renderer; this.attr = attr; this.dstPixels = dstPixels; this.srcPixels = srcPixels; this.profileResults = profileResults; } public void run() { long[] times = new long[6]; for (int a = 0; a < times.length; a++) { times[a] = System.currentTimeMillis(); for (int b = 0; b < 100; b++) { Arrays.fill(dstPixels.getPixels(), 0); renderer.createShadow(srcPixels, dstPixels, attr.getShadowKernelRadius(), attr.getShadowColor()); } times[a] = System.currentTimeMillis() - times[a]; } Arrays.sort(times); profileResults.store(renderer, attr.getShadowKernelRadius(), times[times.length / 2]); } } // frontload most expensive renderers first: Collection<ShadowRenderer> renderers = Arrays.asList( new OriginalGaussianShadowRenderer(), new GaussianShadowRenderer(), new DoubleBoxShadowRenderer(), new BoxShadowRenderer()); ProfileResults results; QDialog dialog; JProgressBar progressBar; ShadowRendererDemo demo; Frame frame; public Profiler(ShadowRendererDemo demo) { this.demo = demo; frame = (Frame) SwingUtilities.getWindowAncestor(demo); progressBar = new JProgressBar(SwingConstants.HORIZONTAL, 0, 100); progressBar.setIndeterminate(true); JComponent content = QDialog.createContentPanel( "Profiling ShadowRenderers...", "Please wait while I test the execution time for different shadow configurations.", progressBar, true); DialogFooter footer = DialogFooter.createDialogFooter( DialogFooter.CANCEL_OPTION, EscapeKeyBehavior.TRIGGERS_CANCEL); dialog = new QDialog(frame, "Profiling", QDialog.getIcon(QDialog.INFORMATION_MESSAGE), content, footer, true); footer.getButton(DialogFooter.CANCEL_OPTION) .addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); } }); } public ProfileResults getResults() { if (results == null) { results = createResults(); } return results; } protected ProfileResults createResults() { ProfileResults returnValue = new ProfileResults(); AtomicBoolean isCancelled = new AtomicBoolean(false); AtomicBoolean isComplete = new AtomicBoolean(false); dialog.pack(); dialog.setLocationRelativeTo(frame); Thread profileThread = new Thread("ShadowRenderer-Profiler") { @Override public void run() { profileRenderers(returnValue, dialog, progressBar, renderers, isCancelled, isComplete); } }; profileThread.start(); dialog.setVisible(true); if (!isComplete.get()) isCancelled.set(true); if (isComplete.get()) return returnValue; return null; } private void profileRenderers(ProfileResults profileResults, final QDialog dialog, final JProgressBar progressBar, Collection<ShadowRenderer> renderers, AtomicBoolean isCancelled, AtomicBoolean isComplete) { try { ARGBPixels srcPixels = new ARGBPixels(demo.srcImage); demo.srcImage.getRaster().getDataElements(0, 0, srcPixels.getWidth(), srcPixels.getHeight(), srcPixels.getPixels()); List<Runnable> runnables = new LinkedList<>(); for (ShadowRenderer renderer : renderers) { float min = 0; float max = 25; // load max first so we front more expensive things at the // beginning of progress bar updates for (float kernelSize = max; kernelSize >= min; kernelSize -= .5f) { ShadowAttributes attr = new ShadowAttributes(0, 0, kernelSize, Color.black); int k = renderer.getKernel(attr.getShadowKernelRadius()) .getKernelRadius(); ARGBPixels dstPixels = new ARGBPixels( demo.srcImage.getWidth() + 2 * k, demo.srcImage.getHeight() + 2 * k); runnables.add(new RunSample(profileResults, renderer, attr, srcPixels, dstPixels)); } } SwingUtilities.invokeLater( new UpdateProgressBar(progressBar, 0, runnables.size(), 0)); int ctr = 0; int size = runnables.size(); while (!runnables.isEmpty()) { if (isCancelled.get()) { break; } Runnable runnable = runnables.remove(0); runnable.run(); SwingUtilities.invokeLater( new UpdateProgressBar(progressBar, 0, size, ctr++)); } isComplete.set(runnables.isEmpty()); if (isComplete.get()) profileResults.printTable(); } catch (Throwable t) { t.printStackTrace(); } finally { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dialog.setVisible(false); } }); } } }
package com.qiniu.streaming; import com.qiniu.common.QiniuException; import com.qiniu.http.Client; import com.qiniu.http.Response; import com.qiniu.streaming.model.ActivityRecords; import com.qiniu.streaming.model.StreamAttribute; import com.qiniu.streaming.model.StreamListing; import com.qiniu.streaming.model.StreamStatus; import com.qiniu.util.Auth; import com.qiniu.util.StringMap; import com.qiniu.util.StringUtils; import com.qiniu.util.UrlSafeBase64; import java.util.Iterator; public final class StreamingManager { private final String apiServer; private final String hub; private final Client client; private final Auth auth; public StreamingManager(Auth auth, String hub) { this(auth, hub, "http://pili.qiniuapi.com"); } StreamingManager(Auth auth, String hub, String server) { apiServer = server; this.hub = hub; this.auth = auth; client = new Client(); } public void create(String key) throws QiniuException { String path = ""; String body = String.format("{\"key\":\"%s\"}", key); post(path, body, null); } public StreamAttribute attribute(String key) throws QiniuException { String path = encodeKey(key); return get(path, StreamAttribute.class); } /** * * * @param live * @param prefix * @return Stream */ public ListIterator createStreamListIterator(boolean live, String prefix) { return new ListIterator(live, prefix); } public StreamListing listStreams(boolean live, String prefix, String marker) throws QiniuException { StringMap map = new StringMap(); if (live) { map.put("liveonly", live); } if (!StringUtils.isNullOrEmpty(prefix)) { map.put("prefix", prefix); } if (!StringUtils.isNullOrEmpty(marker)) { map.put("marker", marker); } String path = ""; if (map.size() != 0) { path += "?" + map.formString(); } return get(path, StreamListing.class); } public void disableTill(String key, long epoch) throws QiniuException { String path = encodeKey(key) + "/disabled"; String body = String.format("{\"disabledTill\":%d}", epoch); post(path, body, null); } public void enable(String key) throws QiniuException { disableTill(key, 0); } public StreamStatus status(String key) throws QiniuException { String path = encodeKey(key) + "/live"; return get(path, StreamStatus.class); } public String saveAs(String key, String fileName) throws QiniuException { return saveAs(key, fileName, 0, 0); } public String saveAs(String key, String fileName, long start, long end) throws QiniuException { String path = encodeKey(key) + "/saveas"; String body; if (fileName == null) { body = String.format("{\"start\": %d,\"end\": %d}", start, end); } else { body = String.format("{\"fname\": %s,\"start\": %d,\"end\": %d}", fileName, start, end); } SaveRet r = post(path, body, SaveRet.class); return r.fname; } public ActivityRecords history(String key, long start, long end) throws QiniuException { if (start <= 0 || end < 0 || (start >= end && end != 0)) { throw new QiniuException(new IllegalArgumentException("bad argument" + start + "," + end)); } String path = encodeKey(key) + "/historyactivity?" + start; if (end != 0) { path += "&end=" + end; } return get(path, ActivityRecords.class); } private String encodeKey(String key) { return "/" + UrlSafeBase64.encodeToString(key); } private <T> T get(String path, Class<T> classOfT) throws QiniuException { String url = apiServer + "/v2/hubs/" + hub + "/streams" + path; StringMap headers = auth.authorizationV2(url); Response r = client.get(url, headers); if (classOfT != null) { return r.jsonToObject(classOfT); } return null; } private <T> T post(String path, String body, Class<T> classOfT) throws QiniuException { String url = apiServer + "/v2/hubs/" + hub + "/streams" + path; byte[] b = body.getBytes(); StringMap headers = auth.authorizationV2(url, "POST", b, Client.JsonMime); Response r = client.post(url, b, headers, Client.JsonMime); if (classOfT != null) { return r.jsonToObject(classOfT); } return null; } private static class SaveRet { public String fname; } public class ListIterator implements Iterator<String[]> { private final boolean live; private String marker = null; private String prefix; private QiniuException exception = null; public ListIterator(boolean live, String prefix) { this.live = live; this.prefix = prefix; } public QiniuException exception() { return exception; } @Override public boolean hasNext() { return exception == null && !"".equals(marker); } @Override public String[] next() { try { StreamListing l = listStreams(live, prefix, marker); this.marker = l.marker == null ? "" : l.marker; return l.keys(); } catch (QiniuException e) { this.exception = e; return null; } } @Override public void remove() { throw new UnsupportedOperationException("remove"); } } }
package com.semihunaldi.excelorm; import com.semihunaldi.excelorm.annotations.Excel; import com.semihunaldi.excelorm.annotations.ExcelColumn; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.io.File; import java.io.InputStream; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ExcelReader { public <T extends BaseExcel> List<T> read(InputStream inputStream, Class<T> clazz) throws Exception { List<T> tList = new ArrayList<>(); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream); read(clazz, tList, xssfWorkbook); xssfWorkbook.getPackage().revert(); return tList; } public <T extends BaseExcel> List<T> read(File file, Class<T> clazz) throws Exception { List<T> tList = new ArrayList<>(); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); read(clazz, tList, xssfWorkbook); xssfWorkbook.getPackage().revert(); return tList; } private <T extends BaseExcel> void read(Class<T> clazz, List<T> tList, XSSFWorkbook xssfWorkbook) throws InstantiationException, IllegalAccessException { Excel excelAnnotation = clazz.getAnnotation(Excel.class); if (excelAnnotation != null) { int sheet = excelAnnotation.sheet(); int firstRow = excelAnnotation.firstRow(); int firstCol = excelAnnotation.firstCol(); XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(sheet); for (int rows = firstRow; rows < xssfSheet.getPhysicalNumberOfRows(); rows++) { T t = clazz.newInstance(); updateRowField(t,clazz,rows); XSSFRow row = xssfSheet.getRow(rows); for (int cells = firstCol; cells < row.getPhysicalNumberOfCells(); cells++) { XSSFCell cell = row.getCell(cells); Field field = findFieldByColNumber(clazz, cells); if (field != null) { setFieldValue(t, cell, field); } } tList.add(t); } } } private <T extends BaseExcel> void setFieldValue(T t, XSSFCell cell, Field field) { Object o = getCellValue(cell, field); setFieldValue(t, field, o); } private <T extends BaseExcel> void setFieldValue(T t, Field field, Object o) { try { boolean accessible = field.isAccessible(); field.setAccessible(true); field.set(t, o); field.setAccessible(accessible); } catch (IllegalAccessException e) { //swallow } } private Field findFieldByColNumber(Class clazz, int col) { List<Field> fieldsListWithAnnotation = FieldUtils.getFieldsListWithAnnotation(clazz, ExcelColumn.class); for (Field field : fieldsListWithAnnotation) { ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); if (annotation.col() == col) { return field; } } return null; } private <T extends BaseExcel> void updateRowField(T t, Class clazz, int row) { Field field = FieldUtils.getField(clazz,"_myRow",true); setFieldValue(t,field,row); } private Object getCellValue(XSSFCell cell, Field field) { Class<?> type = field.getType(); try { if (type == String.class) { cell.setCellType(CellType.STRING); return cell.getStringCellValue(); } else if (type == Integer.class) { return Integer.valueOf(getNumericTypesAsString(cell)); } else if (type == Double.class) { return Double.valueOf(getNumericTypesAsString(cell)); } else if (type == BigInteger.class) { return new BigInteger(getNumericTypesAsString(cell)); } else if (type == Long.class) { return Long.valueOf(getNumericTypesAsString(cell)); } else if (type == Boolean.class) { cell.setCellType(CellType.BOOLEAN); return cell.getBooleanCellValue(); } else if(type == Date.class) { return tryToGetDateCellValue(cell,field); } else { cell.setCellType(CellType.STRING); return cell.getStringCellValue(); } } catch (Exception e) { return null; } } private Date tryToGetDateCellValue(XSSFCell cell, Field field) { try { ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); if(annotation != null && StringUtils.isNotBlank(annotation.dateFormat())) { cell.setCellType(CellType.STRING); String stringCellValue = cell.getStringCellValue(); DateTimeFormatter dtf = DateTimeFormat.forPattern(annotation.dateFormat()); DateTime dateTime = dtf.parseDateTime(stringCellValue); return dateTime.toDate(); } else { try { return cell.getDateCellValue(); } catch (Exception e) { return null; } } } catch (Exception e1) { try { return cell.getDateCellValue(); } catch (Exception e) { return null; } } } private String getNumericTypesAsString(XSSFCell cell) { cell.setCellType(CellType.STRING); return cell.getStringCellValue(); } }
package com.trezoragent.gui; import com.trezoragent.sshagent.ReadTrezorData; import com.trezoragent.utils.AgentConstants; import com.trezoragent.utils.AgentUtils; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.border.Border; /** * * @author martin.lizner */ public class PassphraseDialog extends JFrame { final Color WINDOW_BORDER_COLOR = new Color(114, 159, 207); // = logo outter frame color private final int FRAME_XSIZE = 230; private final int FRAME_YSIZE = 150; private static Point mouseDownCompCoords; private ReadTrezorData passphraseData; private JLabel deviceLabel; private JLabel passcodeLabel; private JPasswordField passcodeField; private JButton enterBtn; private JButton cancelBtn; JPanel labelPanel = new JPanel(); JPanel passphrasePanel = new JPanel(); JPanel passphraseWindowPanel = new JPanel(); JPanel enterPanel = new JPanel(); JPanel buttonPanel = new JPanel(); public PassphraseDialog() { init(); setIconImages(AgentUtils.getAllIcons()); // icon addInputArea(); // text input field addButtonArea(); // enter + cancel buttons addGlobalArea(); // outer panel } private void init() { passphraseData = new ReadTrezorData(); setUndecorated(true); setResizable(false); setAlwaysOnTop(true); setPreferredSize(new Dimension(FRAME_XSIZE, FRAME_YSIZE)); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(dim.width / 2 - getContentPane().getSize().width / 2, dim.height / 2 - getSize().height / 2); setVisible(false); pack(); addAbilityToMoveWindow(this); } private void addInputArea() { labelPanel.setLayout(new GridLayout(3, 1)); Border labelsPadding = BorderFactory.createEmptyBorder(0, 0, 15, 0); labelPanel.setBorder(labelsPadding); deviceLabel = new JLabel(AgentConstants.APP_PUBLIC_NAME.toUpperCase()); Icon icon = new ImageIcon(TrayProcess.createImage(AgentConstants.ICON24_PATH, AgentConstants.ICON_DESCRIPTION)); deviceLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0)); deviceLabel.setIcon(icon); deviceLabel.setIconTextGap(10); deviceLabel.setFont(new Font(null, Font.BOLD, 15)); passcodeLabel = new JLabel("Please enter passphrase:"); passcodeField = new JPasswordField(); passcodeField.setBackground(Color.white); labelPanel.add(deviceLabel, BorderLayout.NORTH); labelPanel.add(passcodeLabel, BorderLayout.CENTER); labelPanel.add(passcodeField, BorderLayout.SOUTH); } private void addButtonArea() { buttonPanel.setLayout(new GridLayout(1, 2)); enterBtn = new JButton("ENTER"); enterBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getPassphraseData().setTrezorData(new String(passcodeField.getPassword())); dispose(); // close passphrase window } }); buttonPanel.add(enterBtn); getRootPane().setDefaultButton(enterBtn); cancelBtn = new JButton("CANCEL"); cancelBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getPassphraseData().setTrezorData(AgentConstants.PASSPHRASE_CANCELLED_MSG); dispose(); // close passphrase window } }); buttonPanel.add(cancelBtn); } private void addGlobalArea() { Border framePadding = BorderFactory.createEmptyBorder(1, 8, 8, 8); Border lineBorder = BorderFactory.createLineBorder(WINDOW_BORDER_COLOR, 2, false); passphrasePanel.setBorder(framePadding); passphraseWindowPanel.setBorder(lineBorder); passphrasePanel.setLayout(new BorderLayout()); passphrasePanel.add(labelPanel, BorderLayout.CENTER); passphrasePanel.add(buttonPanel, BorderLayout.SOUTH); passphraseWindowPanel.add(passphrasePanel); add(passphraseWindowPanel); } public ReadTrezorData getPassphraseData() { return passphraseData; } private void addAbilityToMoveWindow(final JFrame f) { f.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { mouseDownCompCoords = null; } @Override public void mousePressed(MouseEvent e) { mouseDownCompCoords = e.getPoint(); } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseClicked(MouseEvent e) { } }); f.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { Point currCoords = e.getLocationOnScreen(); f.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y); } }); } }
package com.yjz.microweb.http; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import javax.servlet.Filter; import javax.servlet.ServletException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import com.yjz.microweb.MicrowebException; import com.yjz.microweb.annotation.FilterClass; import com.yjz.microweb.annotation.FilterDef; import com.yjz.microweb.annotation.FilterInitParam; import com.yjz.microweb.annotation.FilterName; import com.yjz.microweb.annotation.FilterUrlPattern; import com.yjz.microweb.cache.ResourceCache; import com.yjz.microweb.cache.ResourceCacheDefault; import com.yjz.microweb.context.MicrowebServletContext; import com.yjz.microweb.filter.FilterMap; import com.yjz.microweb.filter.MicrowebFilterConfig; import com.yjz.microweb.servlet.MicrowebServletConfig; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponse; /** * HttpServlet * * @ClassName HttpCoreServer * @Description TODO() * @author biw * @Date 2017531 1:19:12 * @version 1.0.0 */ public class HttpCoreServer { private static final Logger logger = LoggerFactory.getLogger(HttpCoreServer.class); private static HttpCoreServer httpCoreServer = new HttpCoreServer(); protected XmlWebApplicationContext wac; protected DispatcherServlet dispatcherServlet; protected MicrowebServletContext servletContext; protected ResourceCache CACHE = new ResourceCacheDefault(); protected boolean isStaticSupport = true; private HttpCoreServer() { } public static HttpCoreServer instance() { return httpCoreServer; } public void init(String servletContextName) { initServletContext(servletContextName); initWebApplication(); initFilters(); initServlet(); } private void initServletContext(String servletContextName) { this.servletContext = new MicrowebServletContext(servletContextName, servletContextName, servletContextName); } private void initWebApplication() { MicrowebServletConfig servletConfig = new MicrowebServletConfig(this.servletContext); this.wac = new XmlWebApplicationContext(); this.wac.setServletContext(this.servletContext); this.wac.setServletConfig(servletConfig); this.wac.setConfigLocation("classpath*:applicationContext.xml"); this.wac.refresh(); } private void initServlet() { try { this.dispatcherServlet = new DispatcherServlet(this.wac); this.dispatcherServlet.init(this.wac.getServletConfig()); } catch (ServletException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } } private void initFilters() { Map<String, Object> filterDefBeans = this.wac.getBeansWithAnnotation(FilterDef.class); for (Object obj : filterDefBeans.values()) { for (Method method : obj.getClass().getDeclaredMethods()) { FilterName filterNameAnno = method.getAnnotation(FilterName.class); if (filterNameAnno == null) { logger.error("'FilterName' on annotation class " + obj.getClass().getName() + "does not exist."); continue; } FilterClass filterClassAnno = method.getAnnotation(FilterClass.class); if (filterClassAnno == null) { logger.error("'FilterClass' on annotation class " + obj.getClass().getName() + "does not exist."); continue; } FilterInitParam[] filterInitParamAnnos = method.getAnnotationsByType(FilterInitParam.class); Map<String, String> initParams = new HashMap<>(); if (filterInitParamAnnos != null && filterInitParamAnnos.length > 0) { for (FilterInitParam filterInitParamAnno : filterInitParamAnnos) { initParams.put(filterInitParamAnno.paramName(), filterInitParamAnno.paramValue()); } } FilterUrlPattern filterUrlPatternAnno = method.getAnnotation(FilterUrlPattern.class); if (filterUrlPatternAnno == null) { logger.error( "'FilterUrlPattern' on annotation class " + obj.getClass().getName() + "does not exist."); continue; } try { Filter filter = (Filter)filterClassAnno.value().newInstance(); MicrowebFilterConfig conifg = new MicrowebFilterConfig(servletContext); conifg.setFilter(filter); conifg.setFilterName(filterNameAnno.value()); conifg.setInitParameters(initParams); filter.init(conifg); servletContext.addFilter(conifg.getFilterName(), filter); for (String urlPattern : filterUrlPatternAnno.value()) { FilterMap filterMap = new FilterMap(); filterMap.setFilterName(filterNameAnno.value()); filterMap.setURLPattern(urlPattern); servletContext.addFilterMap(filterMap, true); } } catch (InstantiationException | IllegalAccessException | ServletException e) { throw new MicrowebException(e); } } } } public HttpResponse dispach(ChannelHandlerContext ctx, Object msg) { HttpActionAdapter action = HttpActionAdapter4Spring.instance(); if (!(msg instanceof FullHttpRequest)) { return action.doNotHttpRequest(ctx, msg); } FullHttpRequest request = (FullHttpRequest)msg; HttpMethod method = request.method(); if (null == method) { return action.doNullHttpMethod(ctx, request); } String uri = request.uri(); String[] temp = uri.split("\\?"); String shortUri = getRequestURI(temp[0]); Map<String, String[]> parameters = null; if (method.equals(HttpMethod.GET)) { parameters = temp.length > 1 ? getParameters(temp[1]) : new HashMap<>(); } else if (method.equals(HttpMethod.POST)) { parameters = getParametersInBoby(request); } if (method.equals(HttpMethod.GET)) { return action.doGet(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.POST)) { return action.doPost(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.OPTIONS)) { return action.doOptions(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.HEAD)) { return action.doHead(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.PUT)) { return action.doPut(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.PATCH)) { return action.doPatch(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.DELETE)) { return action.doDelete(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.TRACE)) { return action.doTrace(ctx, request, shortUri, parameters); } else if (method.equals(HttpMethod.CONNECT)) { return action.doConnect(ctx, request, shortUri, parameters); } else { return action.doUnContainMethod(ctx, request, shortUri, parameters); } } private String getRequestURI(String fullPath) { return fullPath.replaceAll(servletContext.getContextPath(), ""); } /** * * * @param temp * @return */ private Map<String, String[]> getParameters(String paramNameValueStr) { Map<String, String[]> map = new HashMap<String, String[]>(); String suffix = paramNameValueStr; String[] params = suffix.split("&"); for (String s : params) { String[] keyValues = s.split("="); if(keyValues.length > 1) { String key = keyValues[0]; String[] values = keyValues[1].split(","); map.put(key, values); } } return map; } private Map<String, String[]> getParametersInBoby(FullHttpRequest request) { if (request.content() == null) { return new HashMap<String, String[]>(); } byte[] dst = null; if (request.content().isDirect()) { dst = new byte[request.content().capacity()]; request.content().getBytes(0, dst); } else { dst = request.content().array(); } String bodyContent; try { bodyContent = URLDecoder.decode(new String(dst, "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("request content-type charset should be UTF-8"); throw new MicrowebException(e); } return getParameters(bodyContent); } }
package de.bmoth.modelchecker; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class StateSpaceNode { private final State state; private final Set<StateSpaceNode> successors; public StateSpaceNode(State state) { this.state = state; successors = new HashSet<>(); } public void addSuccessor(StateSpaceNode successor) { successors.add(successor); } @Override public int hashCode() { return state.hashCode(); } @Override public boolean equals(Object o) { return state.equals(o); } @Override public String toString() { return state.toString() + ", successors: " + successors.stream().map(successor -> successor.state).collect(Collectors.toList()); } }
package io.branch.referral; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; /** * <p>Class that provides a chooser dialog with customised share options to share a link. * Class provides customised and easy way of sharing a deep link with other applications. </p> */ class ShareLinkManager { /* The custom chooser dialog for selecting an application to share the link. */ AnimatedDialog shareDlg_; Branch.BranchLinkShareListener callback_; /* List of apps available for sharing. */ private List<ResolveInfo> appList_; /* Intent for sharing with selected application.*/ private Intent shareLinkIntent_; /* Background color for the list view in enabled state. */ private final int BG_COLOR_ENABLED = Color.argb(60, 17, 4, 56); /* Background color for the list view in disabled state. */ private final int BG_COLOR_DISABLED = Color.argb(20, 17, 4, 56); /* Current activity context.*/ Context context_; /* Default height for the list item.*/ private static int viewItemMinHeight = 100; /* Indicates whether a sharing is in progress*/ private boolean isShareInProgress_ =false; private Branch.ShareLinkBuilder builder_; /** * Creates an application selector and shares a link on user selecting the application. * * @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link. * @return Instance of the {@link Dialog} holding the share view. Null if sharing dialog is not created due to any error. */ public Dialog shareLink(Branch.ShareLinkBuilder builder) { builder_ = builder; context_ = builder.getActivity(); callback_ = builder.getCallback(); shareLinkIntent_ = new Intent(Intent.ACTION_SEND); shareLinkIntent_.setType("text/plain"); try { createShareDialog(builder.getPreferredOptions()); } catch (Exception e) { e.printStackTrace(); if (callback_ != null) { callback_.onLinkShareResponse(null, null, new BranchError("Trouble sharing link", BranchError.ERR_BRANCH_NO_SHARE_OPTION)); } else { Log.i("BranchSDK", "Unable create share options. Couldn't find applications on device to share the link."); } } return shareDlg_; } /** * Dismiss the share dialog if showing. Should be called on activity stopping. * * @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation. * A value of true will close the dialog with an animation. Setting this value * to false will close the Dialog immediately. */ public void cancelShareLinkDialog(boolean animateClose) { if (shareDlg_ != null && shareDlg_.isShowing()) { if (animateClose) { // Cancel the dialog with animation shareDlg_.cancel(); } else { // Dismiss the dialog immediately shareDlg_.dismiss(); } } } /** * Create a custom chooser dialog with available share options. * * @param preferredOptions List of {@link io.branch.referral.SharingHelper.SHARE_WITH} options. */ private void createShareDialog(List<SharingHelper.SHARE_WITH> preferredOptions) { final PackageManager packageManager = context_.getPackageManager(); final List<ResolveInfo> preferredApps = new ArrayList<>(); final List<ResolveInfo> matchingApps = packageManager.queryIntentActivities(shareLinkIntent_, PackageManager.MATCH_DEFAULT_ONLY); ArrayList<SharingHelper.SHARE_WITH> packagesFilterList = new ArrayList<>(preferredOptions); /* Get all apps available for sharing and the available preferred apps. */ for (ResolveInfo resolveInfo : matchingApps) { SharingHelper.SHARE_WITH foundMatching = null; String packageName = resolveInfo.activityInfo.packageName; for (SharingHelper.SHARE_WITH PackageFilter : packagesFilterList) { if (resolveInfo.activityInfo != null && packageName.toLowerCase().contains(PackageFilter.toString().toLowerCase())) { foundMatching = PackageFilter; break; } } if (foundMatching != null) { preferredApps.add(resolveInfo); preferredOptions.remove(foundMatching); } } /* Create all app list with copy link item. */ matchingApps.removeAll(preferredApps); matchingApps.addAll(0, preferredApps); matchingApps.add(new CopyLinkItem()); preferredApps.add(new CopyLinkItem()); if (preferredApps.size() > 1) { /* Add more and copy link option to preferred app.*/ if (matchingApps.size() > preferredApps.size()) { preferredApps.add(new MoreShareItem()); } appList_ = preferredApps; } else { appList_ = matchingApps; } /* Copy link option will be always there for sharing. */ final ChooserArrayAdapter adapter = new ChooserArrayAdapter(); final ListView shareOptionListView = new ListView(context_); shareOptionListView.setAdapter(adapter); shareOptionListView.setHorizontalFadingEdgeEnabled(false); shareOptionListView.setBackgroundColor(Color.WHITE); shareOptionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { if (view.getTag() instanceof MoreShareItem) { appList_ = matchingApps; adapter.notifyDataSetChanged(); } else { if (callback_ != null) { callback_.onChannelSelected(((ResolveInfo) view.getTag()).loadLabel(context_.getPackageManager()).toString()); } invokeSharingClient((ResolveInfo) view.getTag()); adapter.selectedPos = pos; adapter.notifyDataSetChanged(); if (shareDlg_ != null) { shareDlg_.cancel(); } } } }); shareDlg_ = new AnimatedDialog(context_); shareDlg_.setContentView(shareOptionListView); shareDlg_.show(); if (callback_ != null) { callback_.onShareLinkDialogLaunched(); } shareDlg_.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (callback_ != null) { callback_.onShareLinkDialogDismissed(); callback_ = null; } // Release context to prevent leaks if (!isShareInProgress_) { context_ = null; builder_ = null; } shareDlg_ = null; } }); } @SuppressWarnings("deprecation") private void invokeSharingClient(final ResolveInfo selectedResolveInfo) { isShareInProgress_ = true; final String channelName = selectedResolveInfo.loadLabel(context_.getPackageManager()).toString(); builder_.getBranch().getShortUrl(builder_.getTags(), channelName, builder_.getFeature(), builder_.getStage(), builder_.getLinkCreationParams(), new Branch.BranchLinkCreateListener() { @Override public void onLinkCreate(String url, BranchError error) { if (error == null) { shareWithClient(selectedResolveInfo, url, channelName); } else { //If there is a default URL specified share it. String defaultUrl = builder_.getDefaultURL(); if (defaultUrl != null && defaultUrl.trim().length() > 0) { shareWithClient(selectedResolveInfo, defaultUrl, channelName); } else { if (callback_ != null) { callback_.onLinkShareResponse(url, channelName, error); } else { Log.i("BranchSDK", "Unable to share link " + error.getMessage()); } } } isShareInProgress_ = false; context_ = null; builder_ = null; } }); } private void shareWithClient(ResolveInfo selectedResolveInfo, String url, String channelName) { if (selectedResolveInfo instanceof CopyLinkItem) { addLinkToClipBoard(url, builder_.getShareMsg()); } else { if (callback_ != null) { callback_.onLinkShareResponse(url, channelName, null); } else { Log.i("BranchSDK", "Shared link with " + channelName); } shareLinkIntent_.setPackage(selectedResolveInfo.activityInfo.packageName); String shareSub = builder_.getShareSub(); if (shareSub != null && shareSub.trim().length() > 0) { shareLinkIntent_.putExtra(Intent.EXTRA_SUBJECT, shareSub); } shareLinkIntent_.putExtra(Intent.EXTRA_TEXT, builder_.getShareMsg() + "\n" + url); context_.startActivity(shareLinkIntent_); } } /** * Adds a given link to the clip board. * * @param url A {@link String} to add to the clip board * @param label A {@link String} label for the adding link */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void addLinkToClipBoard(String url, String label) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(url); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText(label, url); clipboard.setPrimaryClip(clip); } Toast.makeText(context_, builder_.getUrlCopiedMessage(), Toast.LENGTH_SHORT).show(); } /* * Adapter class for creating list of available share options */ private class ChooserArrayAdapter extends BaseAdapter { public int selectedPos = -1; @Override public int getCount() { return appList_.size(); } @Override public Object getItem(int position) { return appList_.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ShareItemView itemView; if (convertView == null) { itemView = new ShareItemView(context_); } else { itemView = (ShareItemView) convertView; } ResolveInfo resolveInfo = appList_.get(position); boolean setSelected = position == selectedPos; itemView.setLabel(resolveInfo.loadLabel(context_.getPackageManager()).toString(), resolveInfo.loadIcon(context_.getPackageManager()), setSelected); itemView.setTag(resolveInfo); itemView.setClickable(false); return itemView; } @Override public boolean isEnabled(int position) { return selectedPos < 0; } } /** * Class for sharing item view to be displayed in the list with Application icon and Name. */ private class ShareItemView extends TextView { Context context_; final int padding = 5; final int leftMargin = 100; public ShareItemView(Context context) { super(context); context_ = context; this.setPadding(leftMargin, padding, padding, padding); this.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); this.setMinWidth(context_.getResources().getDisplayMetrics().widthPixels); } public void setLabel(String appName, Drawable appIcon, boolean isEnabled) { this.setText("\t" + appName); this.setTag(appName); if (appIcon == null) { this.setTextAppearance(context_, android.R.style.TextAppearance_Large); this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } else { this.setTextAppearance(context_, android.R.style.TextAppearance_Medium); this.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null); viewItemMinHeight = Math.max(viewItemMinHeight, (appIcon.getIntrinsicHeight() + padding)); } this.setMinHeight(viewItemMinHeight); this.setTextColor(context_.getResources().getColor(android.R.color.black)); if (isEnabled) { this.setBackgroundColor(BG_COLOR_ENABLED); } else { this.setBackgroundColor(BG_COLOR_DISABLED); } } } /** * Class for sharing item more */ private class MoreShareItem extends ResolveInfo { @Override public CharSequence loadLabel(PackageManager pm) { return builder_.getMoreOptionText(); } @Override public Drawable loadIcon(PackageManager pm) { return builder_.getMoreOptionIcon(); } } /** * Class for Sharing Item copy URl */ private class CopyLinkItem extends ResolveInfo { @Override public CharSequence loadLabel(PackageManager pm) { return builder_.getCopyURlText(); } @Override public Drawable loadIcon(PackageManager pm) { return builder_.getCopyUrlIcon(); } } }
package de.teiesti.postie.recipients; import de.teiesti.postie.Postman; import de.teiesti.postie.Recipient; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * A {@link Mailbox} is a {@link Recipient} that stores accepted {@link Letter}s until they where received. To use a * {@link Mailbox} register it to one or more {@link Postman} with {@link Postman#register(Recipient)}. A {@link * Postman} will put any received {@link Letter} into this {@link Mailbox} using {@link #accept(Object, * Postman)}. You can receive accepted letters with {@link #receive()}. * @param <Letter> type of the letters */ public class Mailbox<Letter> extends SimpleRecipient<Letter> { private final BlockingQueue<Letter> inbox = new LinkedBlockingQueue<>(); /** * Accepts {@link Letter}s and stores it in this {@link Mailbox} until they where received with {@link #receive()}. * * @param letter the {@link Letter} * @param postman the {@link Postman} that delivered the {@link Letter} - not used */ @Override public void accept(Letter letter, Postman postman) { inbox.add(letter); } /** * Returns a {@link Letter} that was put into this {@link Mailbox} with {@link #accept(Object, * Postman)}. A {@link Mailbox} works according to the FIFO principle: {@link #receive()} will return the {@link * Letter} that was accepted the longest time ago. Receiving a {@link Letter} from a {@link Mailbox} will remove * it. A {@link Letter} can only received once. If this {@link Mailbox} does not store a {@link Letter} when this * method is called, it will block until a {@link Letter} was accepted or the blocking {@link Thread} was * interrupted. * * @return the {@link Letter} * * @throws InterruptedException if a waiting {@link Thread} was interrupted */ public Letter receive() throws InterruptedException { return inbox.take(); } /** * Returns if this {@link Mailbox} has a {@link Letter} at the moment. This method returns {@code true} if and * only if {@link #receive()} does not block. But please do not rely on this guarantee in a multi-threaded * environment. Another thread may steal "your" {@link Letter}. * * @return if this {@link Mailbox} stores a {@link Letter} */ public boolean hasLetter() { return !inbox.isEmpty(); } }
package io.branch.referral; import static io.branch.referral.BranchPreinstall.getPreinstallSystemData; import static io.branch.referral.BranchUtil.isTestModeEnabled; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StyleRes; import android.text.TextUtils; import android.view.View; import io.branch.referral.Defines.PreinstallKey; import io.branch.referral.ServerRequestGetLATD.BranchLastAttributedTouchDataListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import io.branch.indexing.BranchUniversalObject; import io.branch.referral.network.BranchRemoteInterface; import io.branch.referral.util.BRANCH_STANDARD_EVENT; import io.branch.referral.util.BranchEvent; import io.branch.referral.util.CommerceEvent; import io.branch.referral.util.LinkProperties; /** * <p> * The core object required when using Branch SDK. You should declare an object of this type at * the class-level of each Activity or Fragment that you wish to use Branch functionality within. * </p> * <p> * Normal instantiation of this object would look like this: * </p> * <!-- * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * Branch.getInstance(this.getApplicationContext()) // from an Activity * Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment * </pre> * --> */ public class Branch implements BranchViewHandler.IBranchViewEvents, SystemObserver.AdsParamsFetchEvents, InstallListener.IInstallReferrerEvents { private static final String BRANCH_LIBRARY_VERSION = "io.branch.sdk.android:library:" + BuildConfig.VERSION_NAME; private static final String GOOGLE_VERSION_TAG = "!SDK-VERSION-STRING!" + ":" + BRANCH_LIBRARY_VERSION; /** * Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that * are shared with others directly as a user action, via social media for instance. */ public static final String FEATURE_TAG_SHARE = "share"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated * with a referral program, incentivized or not. */ public static final String FEATURE_TAG_REFERRAL = "referral"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as * referral actions by users of an app using an 'invite contacts' feature for instance. */ public static final String FEATURE_TAG_INVITE = "invite"; /** * Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer. */ public static final String FEATURE_TAG_DEAL = "deal"; /** * Hard-coded {@link String} that denotes a link tagged as a gift action within a service or * product. */ public static final String FEATURE_TAG_GIFT = "gift"; /** * The code to be passed as part of a deal or gift; retrieved from the Branch object as a * tag upon initialisation. Of {@link String} format. */ public static final String REDEEM_CODE = "$redeem_code"; /** * <p>Default value of referral bucket; referral buckets contain credits that are used when users * are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p> */ public static final String REFERRAL_BUCKET_DEFAULT = "default"; /** * <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions. * Even if they are of 0 value.</p> */ public static final String REFERRAL_CODE_TYPE = "credit"; /** * Branch SDK version for the current release of the Branch SDK. */ public static final int REFERRAL_CREATION_SOURCE_SDK = 2; /** * Key value for referral code as a parameter. */ public static final String REFERRAL_CODE = "referral_code"; /** * The redirect URL provided when the link is handled by a desktop client. */ public static final String REDIRECT_DESKTOP_URL = "$desktop_url"; /** * The redirect URL provided when the link is handled by an Android device. */ public static final String REDIRECT_ANDROID_URL = "$android_url"; /** * The redirect URL provided when the link is handled by an iOS device. */ public static final String REDIRECT_IOS_URL = "$ios_url"; /** * The redirect URL provided when the link is handled by a large form-factor iOS device such as * an iPad. */ public static final String REDIRECT_IPAD_URL = "$ipad_url"; /** * The redirect URL provided when the link is handled by an Amazon Fire device. */ public static final String REDIRECT_FIRE_URL = "$fire_url"; /** * The redirect URL provided when the link is handled by a Blackberry device. */ public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url"; /** * The redirect URL provided when the link is handled by a Windows Phone device. */ public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url"; public static final String OG_TITLE = "$og_title"; public static final String OG_DESC = "$og_description"; public static final String OG_IMAGE_URL = "$og_image_url"; public static final String OG_VIDEO = "$og_video"; public static final String OG_URL = "$og_url"; /** * Unique identifier for the app in use. */ public static final String OG_APP_ID = "$og_app_id"; /** * {@link String} value denoting the deep link path to override Branch's default one. By * default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value, * Branch will use yourapp://'$deeplink_path'?link_click_id=12345 */ public static final String DEEPLINK_PATH = "$deeplink_path"; /** * {@link String} value indicating whether the link should always initiate a deep link action. * By default, unless overridden on the dashboard, Branch will only open the app if they are * 100% sure the app is installed. This setting will cause the link to always open the app. * Possible values are "true" or "false" */ public static final String ALWAYS_DEEPLINK = "$always_deeplink"; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user applying the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERREE = 0; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user who created the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, both the creator and applicant receive credit */ public static final int REFERRAL_CODE_LOCATION_BOTH = 3; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * the referral code can be applied continually. */ public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * a user can only apply a specific referral code once. */ public static final int REFERRAL_CODE_AWARD_UNIQUE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used an * unlimited number of times. */ public static final int LINK_TYPE_UNLIMITED_USE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used only * once. After initial use, subsequent attempts will not validate. */ public static final int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 2000; /** * <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a * looping task before triggering an actual connection close during a session close action.</p> */ private static final int PREVENT_CLOSE_TIMEOUT = 500; /* Json object containing key-value pairs for debugging deep linking */ private JSONObject deeplinkDebugParams_; private static boolean disableDeviceIDFetch_; private boolean enableFacebookAppLinkCheck_ = false; private static boolean isSimulatingInstalls_; static boolean ignoreIntent_ = false; private static boolean bypassCurrentActivityIntentState_ = false; static boolean checkInstallReferrer_ = true; private static long playStoreReferrerFetchTime = 1500; public static final long NO_PLAY_STORE_REFERRER_WAIT = 0; /** * <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of * the class during application runtime.</p> */ private static Branch branchReferral_; private BranchRemoteInterface branchRemoteInterface_; private PrefHelper prefHelper_; private final DeviceInfo deviceInfo_; private Context context_; final Object lock; private Semaphore serverSema_; private final ServerRequestQueue requestQueue_; private int networkCount_; private boolean hasNetwork_; private Map<BranchLinkData, String> linkCache_; /* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */ private static boolean isAutoSessionMode_ = false; /* Set to true when {@link Activity} life cycle callbacks are registered. */ private static boolean isActivityLifeCycleCallbackRegistered_ = false; /* Enumeration for defining session initialisation state. */ enum SESSION_STATE { INITIALISED, INITIALISING, UNINITIALISED } enum INTENT_STATE { PENDING, READY } /* Holds the current intent state. Default is set to PENDING. */ private INTENT_STATE intentState_ = INTENT_STATE.PENDING; /* Holds the current Session state. Default is set to UNINITIALISED. */ private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED; /* Instance of share link manager to share links automatically with third party applications. */ private ShareLinkManager shareLinkManager_; /* The current activity instance for the application.*/ WeakReference<Activity> currentActivityReference_; /* Key to indicate whether the Activity was launched by Branch or not. */ private static final String AUTO_DEEP_LINKED = "io.branch.sdk.auto_linked"; /* Key for Auto Deep link param. The activities which need to automatically deep linked should define in this in the activity metadata. */ private static final String AUTO_DEEP_LINK_KEY = "io.branch.sdk.auto_link_keys"; /* Path for $deeplink_path or $android_deeplink_path to auto deep link. The activities which need to automatically deep linked should define in this in the activity metadata. */ private static final String AUTO_DEEP_LINK_PATH = "io.branch.sdk.auto_link_path"; /* Key for disabling auto deep link feature. Setting this to true in manifest will disable auto deep linking feature. */ private static final String AUTO_DEEP_LINK_DISABLE = "io.branch.sdk.auto_link_disable"; /*Key for defining a request code for an activity. should be added as a metadata for an activity. This is used as a request code for launching a an activity on auto deep link. */ private static final String AUTO_DEEP_LINK_REQ_CODE = "io.branch.sdk.auto_link_request_code"; /* Request code used to launch and activity on auto deep linking unless DEF_AUTO_DEEP_LINK_REQ_CODE is not specified for teh activity in manifest.*/ private static final int DEF_AUTO_DEEP_LINK_REQ_CODE = 1501; private final ConcurrentHashMap<String, String> instrumentationExtraData_; /* In order to get Google's advertising ID an AsyncTask is needed, however Fire OS does not require AsyncTask, so isGAParamsFetchInProgress_ would remain false */ private boolean isGAParamsFetchInProgress_ = false; private static String cookieBasedMatchDomain_ = "app.link"; // Domain name used for cookie based matching. private static int LATCH_WAIT_UNTIL = 2500; //used for getLatestReferringParamsSync and getFirstReferringParamsSync, fail after this many milliseconds /* List of keys whose values are collected from the Intent Extra.*/ private static final String[] EXTERNAL_INTENT_EXTRA_KEY_WHITE_LIST = new String[]{ "extra_launch_uri", // Key for embedded uri in FB ads triggered intents "branch_intent" // A boolean that specifies if this intent is originated by Branch }; private CountDownLatch getFirstReferringParamsLatch = null; private CountDownLatch getLatestReferringParamsLatch = null; /* Flag for checking of Strong matching is waiting on GAID fetch */ private boolean performCookieBasedStrongMatchingOnGAIDAvailable = false; private boolean isInstantDeepLinkPossible = false; private BranchActivityLifecycleObserver activityLifeCycleObserver; /* Flag to turn on or off instant deeplinking feature. IDL is disabled by default */ private static boolean disableInstantDeepLinking = true; private final TrackingController trackingController; /** * <p>The main constructor of the Branch class is private because the class uses the Singleton * pattern.</p> * * <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p> * * @param context A {@link Context} from which this call was made. */ private Branch(@NonNull Context context) { prefHelper_ = PrefHelper.getInstance(context); trackingController = new TrackingController(context); branchRemoteInterface_ = BranchRemoteInterface.getDefaultBranchRemoteInterface(context); deviceInfo_ = DeviceInfo.initialize(context); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); lock = new Object(); networkCount_ = 0; hasNetwork_ = true; linkCache_ = new HashMap<>(); instrumentationExtraData_ = new ConcurrentHashMap<>(); if (!trackingController.isTrackingDisabled()) { // Do not get GAID when tracking is disabled isGAParamsFetchInProgress_ = deviceInfo_.getSystemObserver().prefetchAdsParams(context,this); } } public Context getApplicationContext() { return context_; } /** * Sets a custom Branch Remote interface for handling RESTful requests. Call this for implementing a custom network layer for handling communication between * Branch SDK and remote Branch server * * @param remoteInterface A instance of class extending {@link BranchRemoteInterface} with implementation for abstract RESTful GET or POST methods */ public void setBranchRemoteInterface(BranchRemoteInterface remoteInterface) { branchRemoteInterface_ = remoteInterface; } /** * <p> * Enables the test mode for the SDK. This will use the Branch Test Keys. * This will also enable debug logs. * Note: This is same as setting "io.branch.sdk.TestMode" to "True" in Manifest file * </p> */ public static void enableTestMode() { BranchUtil.setTestMode(true); enableDebugMode(); } /** * <p> * Disables the test mode for the SDK. * This will also disable debug logs. * </p> */ public static void disableTestMode() { BranchUtil.setTestMode(false); disableDebugMode(); } /** * Enables debug mode for the SDK. * @deprecated use {@link Branch#enableDebugMode()} */ public void setDebug() { enableDebugMode(); } /** * Enables debug mode for the SDK and log the SDK Version Declaration Tag. */ public static void enableDebugMode() { BranchUtil.setDebugMode(true); PrefHelper.LogAlways(GOOGLE_VERSION_TAG); } /** * Disables debug mode for the SDK. */ public static void disableDebugMode() { BranchUtil.setDebugMode(false); } /** * <p>Sets a custom base URL for all calls to the Branch API. Requires https.</p> * @param url The {@link String} URL base URL that the Branch API uses. */ public static void setAPIUrl(String url) { PrefHelper.setAPIUrl(url); } /** * <p>Sets a custom CDN base URL.</p> * @param url The {@link String} base URL for CDN endpoints. */ public static void setCDNBaseUrl(String url) { PrefHelper.setCDNBaseUrl(url); } /** * Method to change the Tracking state. If disabled SDK will not track any user data or state. SDK will not send any network calls except for deep linking when tracking is disabled */ public void disableTracking(boolean disableTracking) { trackingController.disableTracking(context_, disableTracking); } /** * Checks if tracking is disabled. See {@link #disableTracking(boolean)} * * @return {@code true} if tracking is disabled */ public boolean isTrackingDisabled() { return trackingController.isTrackingDisabled(); } /** * @deprecated This method is deprecated since play store referrer is enabled by default from v2.9.1. * Please use {@link #setPlayStoreReferrerCheckTimeout(long)} instead. */ public static void enablePlayStoreReferrer(long delay) { setPlayStoreReferrerCheckTimeout(delay); } /** * Since play store referrer broadcast from google play is few millisecond delayed Branch will delay the collecting deep link data on app install by {@link #playStoreReferrerFetchTime} millisecond * This will allow branch to provide for more accurate tracking and attribution. This will delay branch init only the first time user open the app. * This method allows to override the maximum wait time for play store referrer to arrive. Set it to {@link Branch#NO_PLAY_STORE_REFERRER_WAIT} if you don't want to wait for play store referrer * <p> * Note: as of our testing 4/2017 a 1500 milli sec wait time is enough to capture more than 90% of the install referrer case * * @param delay {@link Long} Maximum wait time for install referrer broadcast in milli seconds. Set to {@link Branch#NO_PLAY_STORE_REFERRER_WAIT} if you don't want to wait for play store referrer */ public static void setPlayStoreReferrerCheckTimeout(long delay) { checkInstallReferrer_ = delay > 0; playStoreReferrerFetchTime = delay; } /** * <p> * Disables or enables the instant deep link functionality. * </p> * * @param disableIDL Value {@code true} disables the instant deep linking. Value {@code false} enables the instant deep linking. */ public static void disableInstantDeepLinking(boolean disableIDL) { disableInstantDeepLinking = disableIDL; } /** * <p>Singleton method to return the pre-initialised object of the type {@link Branch}. * Make sure your app is instantiating {@link BranchApp} before calling this method * or you have created an instance of Branch already by calling getInstance(Context ctx).</p> * * @return An initialised singleton {@link Branch} object */ public static Branch getInstance() { /* Check if BranchApp is instantiated. */ if (branchReferral_ == null) { PrefHelper.Debug("Branch instance is not created yet. Make sure you have initialised Branch. [Consider Calling getInstance(Context ctx) if you still have issue.]"); } else if (isAutoSessionMode_) { /* Check if Activity life cycle callbacks are set if in auto session mode. */ if (!isActivityLifeCycleCallbackRegistered_) { PrefHelper.Debug("Branch instance is not properly initialised. Make sure your Application class is extending BranchApp class. " + "If you are not extending BranchApp class make sure you are initialising Branch in your Applications onCreate()"); } } return branchReferral_; } public static Branch getInstance(@NonNull Context context, @NonNull String branchKey) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context.getApplicationContext(); if (branchReferral_.prefHelper_.isValidBranchKey(branchKey)) { boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } } else { PrefHelper.Debug("Branch Key is invalid. Please check your BranchKey"); } return branchReferral_; } private static Branch getBranchInstance(@NonNull Context context, boolean isLive, String branchKey) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); // Configure live or test mode boolean testModeAvailable = BranchUtil.checkTestMode(context); BranchUtil.setTestMode(isLive ? false : testModeAvailable); // If a Branch key is passed already use it. Else read the key if (TextUtils.isEmpty(branchKey)) { branchKey = BranchUtil.readBranchKey(context); } boolean isNewBranchKeySet; if (TextUtils.isEmpty(branchKey)) { PrefHelper.Debug("Warning: Please enter your branch_key in your project's Manifest file!"); isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE); } else { isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); } //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } branchReferral_.context_ = context.getApplicationContext(); /* If {@link Application} is instantiated register for activity life cycle events. */ if (context instanceof Application) { isAutoSessionMode_ = true; branchReferral_.setActivityLifeCycleObserver((Application) context); } } return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getInstance(@NonNull Context context) { return getBranchInstance(context, true, null); } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ public static Branch getTestInstance(@NonNull Context context) { return getBranchInstance(context, false, null); } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getAutoInstance(@NonNull Context context) { isAutoSessionMode_ = true; boolean isTest = BranchUtil.checkTestMode(context); getBranchInstance(context, !isTest, null); getPreinstallSystemData(branchReferral_, context); return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a user is only referrable * if initSession results in a fresh install. Overriding this gives you control of who is referrable. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getAutoInstance(@NonNull Context context, boolean isReferrable) { isAutoSessionMode_ = true; boolean isTest = BranchUtil.checkTestMode(context); getBranchInstance(context, !isTest, null); getPreinstallSystemData(branchReferral_, context); branchReferral_.setIsReferrable(isReferrable); return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * @param branchKey A {@link String} value used to initialize Branch. * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getAutoInstance(@NonNull Context context, @NonNull String branchKey) { isAutoSessionMode_ = true; boolean isTest = BranchUtil.checkTestMode(context); getBranchInstance(context, !isTest, branchKey); if (branchReferral_.prefHelper_.isValidBranchKey(branchKey)) { boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey); //on setting a new key clear link cache and pending requests if (isNewBranchKeySet) { branchReferral_.linkCache_.clear(); branchReferral_.requestQueue_.clear(); } } else { PrefHelper.Debug("Branch Key is invalid. Please check your BranchKey"); } getPreinstallSystemData(branchReferral_, context); return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ public static Branch getAutoTestInstance(@NonNull Context context) { isAutoSessionMode_ = true; getBranchInstance(context, false, null); getPreinstallSystemData(branchReferral_, context); return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a user is only referrable * if initSession results in a fresh install. Overriding this gives you control of who is referrable. * @return An initialised {@link Branch} object. */ public static Branch getAutoTestInstance(@NonNull Context context, boolean isReferrable) { isAutoSessionMode_ = true; getBranchInstance(context, false, null); getPreinstallSystemData(branchReferral_, context); branchReferral_.setIsReferrable(isReferrable); return branchReferral_; } /** * <p>Initialises an instance of the Branch object.</p> * * @param context A {@link Context} from which this call was made. * @return An initialised {@link Branch} object. */ private static Branch initInstance(@NonNull Context context) { return new Branch(context.getApplicationContext()); } // Package Private // For Unit Testing, we need to reset the Branch state static void shutDown() { ServerRequestQueue.shutDown(); PrefHelper.shutDown(); BranchUtil.shutDown(); DeviceInfo.shutDown(); // BranchStrongMatchHelper.shutDown(); // BranchViewHandler.shutDown(); // DeepLinkRoutingValidator.shutDown(); // InstallListener.shutDown(); // InstantAppUtil.shutDown(); // IntegrationValidator.shutDown(); // ShareLinkManager.shutDown(); // UniversalResourceAnalyser.shutDown(); // Release these contexts immediately. if (branchReferral_ != null) { branchReferral_.context_ = null; branchReferral_.currentActivityReference_ = null; } // Reset all of the statics. branchReferral_ = null; bypassCurrentActivityIntentState_ = false; disableInstantDeepLinking = false; isActivityLifeCycleCallbackRegistered_ = false; isAutoSessionMode_ = false; ignoreIntent_ = false; isSimulatingInstalls_ = false; checkInstallReferrer_ = true; } /** * <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has * been initialised, to false - forcing re-initialisation.</p> */ public void resetUserSession() { setInitState(SESSION_STATE.UNINITIALISED); } /** * <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before * considering the request to have failed entirely. Default 5.</p> * * @param retryCount An {@link Integer} specifying the number of times to retry before giving * up and declaring defeat. */ public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount >= 0) { prefHelper_.setRetryCount(retryCount); } } /** * <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request * to the Branch API. Default 3000 ms.</p> * * @param retryInterval An {@link Integer} value specifying the number of milliseconds to * wait before re-attempting a timed-out request. */ public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } /** * <p>Sets the duration in milliseconds that the system should wait for a response before considering * any Branch API call to have timed out. Default 3000 ms.</p> * <p>Increase this to perform better in low network speed situations, but at the expense of * responsiveness to error situation.</p> * * @param timeout An {@link Integer} value specifying the number of milliseconds to wait before * considering the request to have timed out. */ public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } /** * Method to control reading Android ID from device. Set this to true to disable reading the device id. * This method should be called from your {@link Application#onCreate()} method before creating Branch auto instance by calling {@link Branch#getAutoInstance(Context)} * * @param deviceIdFetch {@link Boolean with value true to disable reading the Android id from device} */ public static void disableDeviceIDFetch(Boolean deviceIdFetch) { disableDeviceIDFetch_ = deviceIdFetch; } /** * Returns true if reading device id is disabled * * @return {@link Boolean} with value true to disable reading Andoid ID */ public static boolean isDeviceIDFetchDisabled() { return disableDeviceIDFetch_; } /** * Sets the key-value pairs for debugging the deep link. The key-value set in debug mode is given back with other deep link data on branch init session. * This method should be called from onCreate() of activity which listens to Branch Init Session callbacks * * @param debugParams A {@link JSONObject} containing key-value pairs for debugging branch deep linking */ public void setDeepLinkDebugMode(JSONObject debugParams) { deeplinkDebugParams_ = debugParams; } /** * @deprecated Branch is not listing external apps any more from v2.11.0 */ public void disableAppList() { // Do nothing } /** * <p> * Enable Facebook app link check operation during Branch initialisation. * </p> */ public void enableFacebookAppLinkCheck() { enableFacebookAppLinkCheck_ = true; } /** * Enables or disables app tracking with Branch or any other third parties that Branch use internally * * @param isLimitFacebookTracking {@code true} to limit app tracking */ public void setLimitFacebookTracking(boolean isLimitFacebookTracking) { prefHelper_.setLimitFacebookTracking(isLimitFacebookTracking); } /** * <p>Add key value pairs to all requests</p> */ public void setRequestMetadata(@NonNull String key, @NonNull String value) { prefHelper_.setRequestMetadata(key, value); } /** * <p> * This API allows to tag the install with custom attribute. Add any key-values that qualify or distinguish an install here. * Please make sure this method is called before the Branch init, which is on the onStartMethod of first activity. * A better place to call this method is right after Branch#getAutoInstance() * </p> */ public Branch addInstallMetadata(@NonNull String key, @NonNull String value) { prefHelper_.addInstallMetadata(key, value); return this; } /** * <p> * wrapper method to add the pre-install campaign analytics * </p> */ public Branch setPreinstallCampaign(@NonNull String preInstallCampaign) { addInstallMetadata(PreinstallKey.campaign.getKey(), preInstallCampaign); return this; } /** * <p> * wrapper method to add the pre-install campaign analytics * </p> */ public Branch setPreinstallPartner(@NonNull String preInstallPartner) { addInstallMetadata(PreinstallKey.partner.getKey(), preInstallPartner); return this; } /** * <p> * Add key value pairs from the injected modules to all requests * </p> */ public void addModule(JSONObject module) { if (module!=null) { Iterator<String> keys = module.keys(); while (keys.hasNext()) { String key = keys.next(); if (!TextUtils.isEmpty(key)) { try { prefHelper_.addSecondaryRequestMetadata(key, module.getString(key)); } catch (JSONException ignore) { } } } } } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchUniversalReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback) { initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback) { initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchUniversalReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, Activity activity) { initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, Activity activity) { initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchUniversalReferralInitListener callback, Uri data) { readAndStripParam(data, null); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, Uri data) { readAndStripParam(data, null); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchUniversalReferralInitListener callback, Uri data, Activity activity) { readAndStripParam(data, activity); initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, Uri data, Activity activity) { readAndStripParam(data, activity); initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession() { initUserSessionInternal((BranchReferralInitListener) null, null); return true; } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(Activity activity) { initUserSessionInternal((BranchReferralInitListener) null, activity); return true; } /** * <p>Force initialises a session with the Branch API, assigning a {@link BranchReferralInitListener} * to perform an action upon successful initialisation. Will not wait for new intent onResume.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSessionForced(BranchReferralInitListener callback) { enableForcedSession(); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that * led to this * initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(Uri data) { readAndStripParam(data, null); initUserSessionInternal((BranchReferralInitListener) null, null); return true; } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that led to this * initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(Uri data, Activity activity) { readAndStripParam(data, activity); initUserSessionInternal((BranchReferralInitListener) null, activity); return true; } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable) { setIsReferrable(isReferrable); initUserSessionInternal((BranchReferralInitListener) null, (Activity) null); return true; } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action, and supplying the calling {@link Activity} for context.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable, @NonNull Activity activity) { setIsReferrable(isReferrable); initUserSessionInternal((BranchReferralInitListener) null, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Uri data) { setIsReferrable(isReferrable); readAndStripParam(data, null); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { setIsReferrable(isReferrable); readAndStripParam(data, null); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) { setIsReferrable(isReferrable); readAndStripParam(data, activity); initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) { setIsReferrable(isReferrable); readAndStripParam(data, activity); initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable) { setIsReferrable(isReferrable); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) { setIsReferrable(isReferrable); initUserSessionInternal(callback, null); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Activity activity) { setIsReferrable(isReferrable); initUserSessionInternal(callback, activity); return true; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { setIsReferrable(isReferrable); initUserSessionInternal(callback, activity); return true; } public boolean reInitSession(Activity activity, BranchUniversalReferralInitListener callback) { return reInitSession(activity, new BranchUniversalReferralInitWrapper(callback)); } /** * Re-Initialize a session. * This solves a very specific use case, whereas the app is already in the foreground and a new * intent with a Uri is delivered to the activity. In this case we want to re-initialize the * session and call back with the decoded parameters. Note that Uri can also be stored as an extra * under the field "branch" * * @param activity The calling {@link Activity} for context. * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialization of the session * with the Branch API. * @return A {@link boolean} value that returns <i>false</i> if unsuccessful. */ public boolean reInitSession(Activity activity, BranchReferralInitListener callback) { if (activity == null) return false; Intent intent = activity.getIntent(); if (intent != null) { currentActivityReference_ = new WeakReference<>(activity); // Re-Initializing with a Uri indicates that we want to fetch the data before we return. Uri uri = intent.getData(); String pushNotifUrl = intent.getStringExtra(Defines.IntentKeys.BranchURI.getKey()); if (uri == null && !TextUtils.isEmpty(pushNotifUrl)) { uri = Uri.parse(pushNotifUrl); } if (uri != null) { // Let's indicate that the app was initialized with this uri. prefHelper_.setExternalIntentUri(uri.toString()); // We need to set the AndroidAppLinkURL as well prefHelper_.setAppLink(uri.toString()); // Now, actually initialize the new session. readAndStripParam(uri, activity); } initializeSession(callback, false); return true; } else { return false; } } private void initUserSessionInternal(BranchUniversalReferralInitListener callback, Activity activity) { BranchUniversalReferralInitWrapper branchUniversalReferralInitWrapper = new BranchUniversalReferralInitWrapper(callback); initUserSessionInternal(branchUniversalReferralInitWrapper, activity); } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity) { if (activity != null) { currentActivityReference_ = new WeakReference<>(activity); } // If an instant deeplink is possible then call init session immediately. This should proceed to a normal open call if (isInstantDeepLinkPossible) { callback.onInitFinished(getLatestReferringParams(), null); addExtraInstrumentationData(Defines.Jsonkey.InstantDeepLinkSession.getKey(), "true"); isInstantDeepLinkPossible = false; checkForAutoDeepLinkConfiguration(); return; } initializeSession(callback, true); } /* * <p>Closes the current session. Should be called by on getting the last actvity onStop() event. * </p> */ void closeSessionInternal() { executeClose(); prefHelper_.setExternalIntentUri(null); trackingController.updateTrackingState(context_); // Update the tracking state for next cold start } /** * Clears all pending requests in the queue */ void clearPendingRequests() { requestQueue_.clear(); } /** * <p> * Enabled Strong matching check using chrome cookies. This method should be called before * Branch#getAutoInstance(Context).</p> * * @param cookieMatchDomain The domain for the url used to match the cookie (eg. example.app.link) */ public static void enableCookieBasedMatching(String cookieMatchDomain) { cookieBasedMatchDomain_ = cookieMatchDomain; } /** * <p> * Enabled Strong matching check using chrome cookies. This method should be called before * Branch#getAutoInstance(Context).</p> * * @param cookieMatchDomain The domain for the url used to match the cookie (eg. example.app.link) * @param delay Time in millisecond to wait for the strong match to check to finish before Branch init session is called. * Default time is 750 msec. */ public static void enableCookieBasedMatching(String cookieMatchDomain, int delay) { cookieBasedMatchDomain_ = cookieMatchDomain; BranchStrongMatchHelper.getInstance().setStrongMatchUrlHitDelay(delay); } /** * <p>Perform the state-safe actions required to terminate any open session, and report the * closed application event to the Branch API.</p> */ private void executeClose() { if (initState_ != SESSION_STATE.UNINITIALISED) { if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req instanceof ServerRequestRegisterInstall || req instanceof ServerRequestRegisterOpen) { requestQueue_.dequeue(); } } else { if (!requestQueue_.containsClose()) { ServerRequest req = new ServerRequestRegisterClose(context_); handleNewRequest(req); } } setInitState(SESSION_STATE.UNINITIALISED); } } private void readAndStripParam(Uri data, Activity activity) { if (!disableInstantDeepLinking && intentState_ == INTENT_STATE.READY && initState_ != SESSION_STATE.INITIALISED && !checkIntentForSessionRestart(activity.getIntent())) { extractSessionParamsForIDL(data, activity); } if (bypassCurrentActivityIntentState_) { intentState_ = INTENT_STATE.READY; } if (intentState_ == INTENT_STATE.READY) { // Capture the intent URI and extra for analytics in case started by external intents such as google app search extractExternalUriAndIntentExtras(data, activity); // if branch link is detected we don't need to look for click ID or app link anymore and can terminate early if (extractBranchLinkFromIntentExtra(activity)) return; // Check for link click id or app link if (!isActivityLaunchedFromHistory(activity)) { // if click ID is detected we don't need to look for app link anymore and can terminate early if (extractClickID(data, activity)) return; // Check if the clicked url is an app link pointing to this app extractAppLink(data, activity); } } } void unlockSDKInitWaitLock() { if (requestQueue_ == null) return; requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.SDK_INIT_WAIT_LOCK); processNextQueueItem(); } private boolean isIntentParamsAlreadyConsumed(Activity activity) { return activity != null && activity.getIntent() != null && activity.getIntent().getBooleanExtra(Defines.IntentKeys.BranchLinkUsed.getKey(), false); } private boolean isActivityLaunchedFromHistory(Activity activity) { return activity != null && activity.getIntent() != null && (activity.getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0; } /** * Package Private. * @return the link which opened this application session if opened by a link click. */ String getSessionReferredLink() { String link = prefHelper_.getExternalIntentUri(); return (link.equals(PrefHelper.NO_STRING_VALUE) ? null : link); } @Override public void onAdsParamsFetchFinished() { isGAParamsFetchInProgress_ = false; requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK); if (performCookieBasedStrongMatchingOnGAIDAvailable) { performCookieBasedStrongMatch(); performCookieBasedStrongMatchingOnGAIDAvailable = false; } else { processNextQueueItem(); } } @Override public void onInstallReferrerEventsFinished() { requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.INSTALL_REFERRER_FETCH_WAIT_LOCK); processNextQueueItem(); } /** * Branch collect the URLs in the incoming intent for better attribution. Branch SDK extensively check for any sensitive data in the URL and skip if exist. * However the following method provisions application to set SDK to collect only URLs in particular form. This method allow application to specify a set of regular expressions to white list the URL collection. * If whitelist is not empty SDK will collect only the URLs that matches the white list. * <p> * This method should be called immediately after calling {@link Branch#getAutoInstance(Context)} * * @param urlWhiteListPattern A regular expression with a URI white listing pattern * @return {@link Branch} instance for successive method calls */ public Branch addWhiteListedScheme(String urlWhiteListPattern) { if (urlWhiteListPattern != null) { UniversalResourceAnalyser.getInstance(context_).addToAcceptURLFormats(urlWhiteListPattern); } return this; } /** * Branch collect the URLs in the incoming intent for better attribution. Branch SDK extensively check for any sensitive data in the URL and skip if exist. * However the following method provisions application to set SDK to collect only URLs in particular form. This method allow application to specify a set of regular expressions to white list the URL collection. * If whitelist is not empty SDK will collect only the URLs that matches the white list. * <p> * This method should be called immediately after calling {@link Branch#getAutoInstance(Context)} * * @param urlWhiteListPatternList {@link List} of regular expressions with URI white listing pattern * @return {@link Branch} instance for successive method calls */ public Branch setWhiteListedSchemes(List<String> urlWhiteListPatternList) { if (urlWhiteListPatternList != null) { UniversalResourceAnalyser.getInstance(context_).addToAcceptURLFormats(urlWhiteListPatternList); } return this; } /** * Branch collect the URLs in the incoming intent for better attribution. Branch SDK extensively check for any sensitive data in the URL and skip if exist. * This method allows applications specify SDK to skip any additional URL patterns to be skipped * <p> * This method should be called immediately after calling {@link Branch#getAutoInstance(Context)} * * @param urlSkipPattern {@link String} A URL pattern that Branch SDK should skip from collecting data * @return {@link Branch} instance for successive method calls */ public Branch addUriHostsToSkip(String urlSkipPattern) { if (!TextUtils.isEmpty(urlSkipPattern)) UniversalResourceAnalyser.getInstance(context_).addToSkipURLFormats(urlSkipPattern); return this; } /** * Check and update the URL / URI Skip list in case an update is available. */ void updateSkipURLFormats() { UniversalResourceAnalyser.getInstance(context_).checkAndUpdateSkipURLFormats(context_); } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value. No callback.</p> * * @param userId A {@link String} value containing the unique identifier of the user. */ public void setIdentity(@NonNull String userId) { setIdentity(userId, null); } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value, with a callback specified to perform a defined action upon successful * response to request.</p> * * @param userId A {@link String} value containing the unique identifier of the user. * @param callback A {@link BranchReferralInitListener} callback instance that will return * the data associated with the user id being assigned, if available. */ public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener callback) { ServerRequestIdentifyUserRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } else { if (req.isExistingID()) { req.handleUserExist(branchReferral_); } } } /** * Gets all available cross platform ids. * * @param callback An instance of {@link io.branch.referral.ServerRequestGetCPID.BranchCrossPlatformIdListener} * to callback with cross platform ids * */ public void getCrossPlatformIds(ServerRequestGetCPID.BranchCrossPlatformIdListener callback) { if (context_ != null) { handleNewRequest(new ServerRequestGetCPID(context_, Defines.RequestPath.GetCPID.getPath(), callback)); } } /** * Gets the available last attributed touch data. The attribution window is set to the value last * saved via PreferenceHelper.setLATDAttributionWindow(). If no value has been saved, Branch * defaults to a 30 day attribution window (SDK sends -1 to request the default from the server). * * @param callback An instance of {@link io.branch.referral.ServerRequestGetLATD.BranchLastAttributedTouchDataListener} * to callback with last attributed touch data * */ public void getLastAttributedTouchData(BranchLastAttributedTouchDataListener callback) { if (context_ != null) { handleNewRequest(new ServerRequestGetLATD(context_, Defines.RequestPath.GetLATD.getPath(), callback)); } } /** * Gets the available last attributed touch data with a custom set attribution window. * * @param callback An instance of {@link io.branch.referral.ServerRequestGetLATD.BranchLastAttributedTouchDataListener} * to callback with last attributed touch data * @param attributionWindow An {@link int} to bound the the window of time in days during which * the attribution data is considered valid. Note that, server side, the * maximum value is 90. * */ public void getLastAttributedTouchData(BranchLastAttributedTouchDataListener callback, int attributionWindow) { if (context_ != null) { handleNewRequest(new ServerRequestGetLATD(context_, Defines.RequestPath.GetLATD.getPath(), callback, attributionWindow)); } } /** * Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs. * If you call setIdentity, this device will have that identity associated with this user until logout is called. * This includes persisting through uninstalls, as we track device id. * * @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity. */ public boolean isUserIdentified() { return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> */ public void logout() { logout(null); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> * * @param callback An instance of {@link io.branch.referral.Branch.LogoutStatusListener} to callback with the logout operation status. */ public void logout(LogoutStatusListener callback) { ServerRequest req = new ServerRequestLogout(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p> */ public void loadRewards() { loadRewards(null); } /** * <p>Retrieves rewards for the current session, with a callback to perform a predefined * action following successful report of state change. You'll then need to call getCredits * in the callback to update the credit totals in your UX.</p> * * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a referral state change. */ public void loadRewards(BranchReferralStateChangedListener callback) { ServerRequest req = new ServerRequestGetRewards(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Retrieve the number of credits available for the "default" bucket.</p> * * @return An {@link Integer} value of the number credits available in the "default" bucket. */ public int getCredits() { return prefHelper_.getCreditCount(); } /** * Returns an {@link Integer} of the number of credits available for use within the supplied * bucket name. * * @param bucket A {@link String} value indicating the name of the bucket to get credits for. * @return An {@link Integer} value of the number credits available in the specified * bucket. */ public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. */ public void redeemRewards(int count) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(int count, BranchReferralStateChangedListener callback) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. */ public void redeemRewards(@NonNull final String bucket, final int count) { redeemRewards(bucket, count, null); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(@NonNull final String bucket, final int count, BranchReferralStateChangedListener callback) { ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(@NonNull final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p>Valid choices:</p> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(@NonNull final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p>Valid choices:</p> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(final String bucket, final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) { ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. */ public void userCompletedAction(@NonNull final String action, JSONObject metadata) { userCompletedAction(action, metadata, null); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". */ public void userCompletedAction(final String action) { userCompletedAction(action, null, null); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events */ public void userCompletedAction(final String action, BranchViewHandler. IBranchViewEvents callback) { userCompletedAction(action, null, callback); } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. * @param callback instance of {@link BranchViewHandler.IBranchViewEvents} to listen Branch view events */ public void userCompletedAction(@NonNull final String action, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { ServerRequest req = new ServerRequestActionCompleted(context_, action, null, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } public void sendCommerceEvent(@NonNull CommerceEvent commerceEvent, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { ServerRequest req = new ServerRequestActionCompleted(context_, BRANCH_STANDARD_EVENT.PURCHASE.getName(), commerceEvent, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } public void sendCommerceEvent(@NonNull CommerceEvent commerceEvent) { sendCommerceEvent(commerceEvent, null, null); } /** * <p>Returns the parameters associated with the link that referred the user. This is only set once, * the first time the user is referred by a link. Think of this as the user referral parameters. * It is also only set if isReferrable is equal to true, which by default is only true * on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the * user already exists from a previous device) and logout.</p> * * @return A {@link JSONObject} containing the install-time parameters as configured * locally. */ public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam); firstReferringParams = appendDebugParams(firstReferringParams); return firstReferringParams; } /** * <p>This function must be called from a non-UI thread! If Branch has no install link data, * and this func is called, it will return data upon initializing, or until LATCH_WAIT_UNTIL. * Returns the parameters associated with the link that referred the user. This is only set once, * the first time the user is referred by a link. Think of this as the user referral parameters. * It is also only set if isReferrable is equal to true, which by default is only true * on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the * user already exists from a previous device) and logout.</p> * * @return A {@link JSONObject} containing the install-time parameters as configured * locally. */ public JSONObject getFirstReferringParamsSync() { getFirstReferringParamsLatch = new CountDownLatch(1); if (prefHelper_.getInstallParams().equals(PrefHelper.NO_STRING_VALUE)) { try { getFirstReferringParamsLatch.await(LATCH_WAIT_UNTIL, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } } String storedParam = prefHelper_.getInstallParams(); JSONObject firstReferringParams = convertParamsStringToDictionary(storedParam); firstReferringParams = appendDebugParams(firstReferringParams); getFirstReferringParamsLatch = null; return firstReferringParams; } /** * <p>Returns the parameters associated with the link that referred the session. If a user * clicks a link, and then opens the app, initSession will return the parameters of the link * and then set them in as the latest parameters to be retrieved by this method. By default, * sessions persist for the duration of time that the app is in focus. For example, if you * minimize the app, these parameters will be cleared when closeSession is called.</p> * * @return A {@link JSONObject} containing the latest referring parameters as * configured locally. */ public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); JSONObject latestParams = convertParamsStringToDictionary(storedParam); latestParams = appendDebugParams(latestParams); return latestParams; } /** * <p>This function must be called from a non-UI thread! If Branch has not been initialized * and this func is called, it will return data upon initialization, or until LATCH_WAIT_UNTIL. * Returns the parameters associated with the link that referred the session. If a user * clicks a link, and then opens the app, initSession will return the parameters of the link * and then set them in as the latest parameters to be retrieved by this method. By default, * sessions persist for the duration of time that the app is in focus. For example, if you * minimize the app, these parameters will be cleared when closeSession is called.</p> * * @return A {@link JSONObject} containing the latest referring parameters as * configured locally. */ public JSONObject getLatestReferringParamsSync() { getLatestReferringParamsLatch = new CountDownLatch(1); try { if (initState_ != SESSION_STATE.INITIALISED) { getLatestReferringParamsLatch.await(LATCH_WAIT_UNTIL, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { } String storedParam = prefHelper_.getSessionParams(); JSONObject latestParams = convertParamsStringToDictionary(storedParam); latestParams = appendDebugParams(latestParams); getLatestReferringParamsLatch = null; return latestParams; } /** * Append the deep link debug params to the original params * * @param originalParams A {@link JSONObject} original referrer parameters * @return A new {@link JSONObject} with debug params appended. */ private JSONObject appendDebugParams(JSONObject originalParams) { try { if (originalParams != null && deeplinkDebugParams_ != null) { if (deeplinkDebugParams_.length() > 0) { PrefHelper.Debug("You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link"); } Iterator<String> keys = deeplinkDebugParams_.keys(); while (keys.hasNext()) { String key = keys.next(); originalParams.put(key, deeplinkDebugParams_.get(key)); } } } catch (Exception ignore) { } return originalParams; } public JSONObject getDeeplinkDebugParams() { if (deeplinkDebugParams_ != null && deeplinkDebugParams_.length() > 0) { PrefHelper.Debug("You're currently in deep link debug mode. Please comment out 'setDeepLinkDebugMode' to receive the deep link parameters from a real Branch link"); } return deeplinkDebugParams_; } /** * <p> Generates a shorl url for the given {@link ServerRequestCreateUrl} object </p> * * @param req An instance of {@link ServerRequestCreateUrl} with parameters create the short link. * @return A url created with the given request if the request is synchronous else null. * Note : This method can be used only internally. Use {@link BranchUrlBuilder} for creating short urls. */ String generateShortLinkInternal(ServerRequestCreateUrl req) { if (!req.constructError_ && !req.handleErrors(context_)) { if (linkCache_.containsKey(req.getLinkPost())) { String url = linkCache_.get(req.getLinkPost()); req.onUrlAvailable(url); return url; } else { if (req.isAsync()) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } /** * <p>Creates options for sharing a link with other Applications. Creates a link with given attributes and shares with the * user selected clients.</p> * * @param builder A {@link BranchShareSheetBuilder} instance to build share link. */ void shareLink(BranchShareSheetBuilder builder) { //Cancel any existing sharing in progress. if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(true); } shareLinkManager_ = new ShareLinkManager(); shareLinkManager_.shareLink(builder); } /** * <p>Cancel current share link operation and Application selector dialog. If your app is not using auto session management, make sure you are * calling this method before your activity finishes inorder to prevent any window leak. </p> * * @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation. * A value of true will close the dialog with an animation. Setting this value * to false will close the Dialog immediately. */ public void cancelShareLinkDialog(boolean animateClose) { if (shareLinkManager_ != null) { shareLinkManager_.cancelShareLinkDialog(animateClose); } } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String generateShortLinkSync(ServerRequestCreateUrl req) { if (trackingController.isTrackingDisabled()) { return req.getLongUrl(); } if (initState_ == SESSION_STATE.INITIALISED) { ServerResponse response = null; try { int timeOut = prefHelper_.getTimeout() + 2000; // Time out is set to slightly more than link creation time to prevent any edge case response = new GetShortLinkTask().execute(req).get(timeOut, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException ignore) { } String url = null; if (req.isDefaultToLongUrl()) { url = req.getLongUrl(); } if (response != null && response.getStatusCode() == HttpURLConnection.HTTP_OK) { try { url = response.getObject().getString("url"); if (req.getLinkPost() != null) { linkCache_.put(req.getLinkPost(), url); } } catch (JSONException e) { e.printStackTrace(); } } return url; } else { PrefHelper.Debug("Warning: User session has not been initialized"); } return null; } private void generateShortLinkAsync(final ServerRequest req) { handleNewRequest(req); } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); if (req != null) { if (!req.isWaitingOnProcessToFinish()) { // All request except Install request need a valid IdentityID if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) { PrefHelper.Debug("Branch Error: User session has not been initialized!"); networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); } // Determine if a session is needed to execute (SDK-271) else if (requestNeedsSession(req) && !isSessionAvailableForRequest()) { networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); } else { BranchPostTask postTask = new BranchPostTask(req); postTask.executeTask(); } } else { networkCount_ = 0; } } else { requestQueue_.remove(null); //In case there is any request nullified remove it. } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } // Determine if a Request needs a Session to proceed. private boolean requestNeedsSession(ServerRequest request) { if (request instanceof ServerRequestInitSession) { return false; } else if (request instanceof ServerRequestCreateUrl) { return false; } // All other Request Types need a session. return true; } // Determine if a Session is available for a Request to proceed. private boolean isSessionAvailableForRequest() { return (hasSession() && hasDeviceFingerPrint()); } private void handleFailure(int index, int statusCode) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize() - 1); } else { req = requestQueue_.peekAt(index); } handleFailure(req, statusCode); } private void handleFailure(final ServerRequest req, int statusCode) { if (req == null) return; req.handleFailure(statusCode, ""); } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req != null) { JSONObject reqJson = req.getPost(); if (reqJson != null) { if (reqJson.has(Defines.Jsonkey.SessionID.getKey())) { req.getPost().put(Defines.Jsonkey.SessionID.getKey(), prefHelper_.getSessionID()); } if (reqJson.has(Defines.Jsonkey.IdentityID.getKey())) { req.getPost().put(Defines.Jsonkey.IdentityID.getKey(), prefHelper_.getIdentityID()); } if (reqJson.has(Defines.Jsonkey.DeviceFingerprintID.getKey())) { req.getPost().put(Defines.Jsonkey.DeviceFingerprintID.getKey(), prefHelper_.getDeviceFingerPrintID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } public TrackingController getTrackingController() { return trackingController; } public DeviceInfo getDeviceInfo() { return deviceInfo_; } PrefHelper getPrefHelper() { return prefHelper_; } boolean isGAParamsFetchInProgress() { return isGAParamsFetchInProgress_; } void setGAParamsFetchInProgress(boolean GAParamsFetchInProgress) { isGAParamsFetchInProgress_ = GAParamsFetchInProgress; } ShareLinkManager getShareLinkManager() { return shareLinkManager_; } void setIntentState(INTENT_STATE intentState) { this.intentState_ = intentState; } void setInitState(SESSION_STATE initState) { this.initState_ = initState; } SESSION_STATE getInitState() { return initState_; } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } public void setInstantDeepLinkPossible(boolean instantDeepLinkPossible) { isInstantDeepLinkPossible = instantDeepLinkPossible; } public boolean isInstantDeepLinkPossible() { return isInstantDeepLinkPossible; } private boolean hasDeviceFingerPrint() { return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void initializeSession(final BranchReferralInitListener callback, boolean isFirstInitialization) { if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) { setInitState(SESSION_STATE.UNINITIALISED); //Report Key error on callback if (callback != null) { callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", BranchError.ERR_BRANCH_KEY_INVALID)); } PrefHelper.Debug("Warning: Please enter your branch_key in your project's res/values/strings.xml!"); return; } else if (isTestModeEnabled()) { PrefHelper.Debug("Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment."); } ServerRequestInitSession initRequest = getInstallOrOpenRequest(callback); if (isFirstInitialization && (getSessionReferredLink() == null || enableFacebookAppLinkCheck_)) { // Check if opened by facebook with deferred install data boolean appLinkRqSucceeded = DeferredAppLinkDataHandler.fetchDeferredAppLinkData( context_, new DeferredAppLinkDataHandler.AppLinkFetchEvents() { @Override public void onAppLinkFetchFinished(String nativeAppLinkUrl) { prefHelper_.setIsAppLinkTriggeredInit(true); // callback returns when app link fetch finishes with success or failure. Report app link checked in both cases if (nativeAppLinkUrl != null) { Uri appLinkUri = Uri.parse(nativeAppLinkUrl); String bncLinkClickId = appLinkUri.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()); if (!TextUtils.isEmpty(bncLinkClickId)) { prefHelper_.setLinkClickIdentifier(bncLinkClickId); } } requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.FB_APP_LINK_WAIT_LOCK); processNextQueueItem(); } }); if (appLinkRqSucceeded) { initRequest.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.FB_APP_LINK_WAIT_LOCK); } } // Re 'forceBranchSession': // Check if new session is being forced. There are two use cases for setting the ForceNewBranchSession to true: // 1. Launch an activity via a push notification while app is in foreground but does not have // the particular activity in the backstack, in such cases, users can't utilize reInitSession() because // it's called from onNewIntent() which is never invoked // todo: this is tricky for users, get rid of ForceNewBranchSession if possible. (if flag is not set, the content from Branch link is lost) // 2. Some users navigate their apps via Branch links so they would have to set ForceNewBranchSession to true // which will blow up the session count in analytics but does the job. Intent intent = getCurrentActivity() != null ? getCurrentActivity().getIntent() : null; boolean forceBranchSession = checkIntentForSessionRestart(intent); // !isFirstInitialization condition equals true only when user calls reInitSession() if (getInitState() == SESSION_STATE.UNINITIALISED || !isFirstInitialization || forceBranchSession) { registerAppInit(initRequest, false); } else if (callback != null) { // Else, let the user know session initialization failed because it's already initialized. callback.onInitFinished(null, new BranchError("Session initialization failed.", BranchError.ERR_BRANCH_ALREADY_INITIALIZED)); } } /** * Registers app init with params filtered from the intent. Unless ignoreIntent = true, this * will wait on the wait locks to complete any pending operations */ private void registerAppInit(@NonNull ServerRequestInitSession request, boolean ignoreIntent) { setInitState(SESSION_STATE.INITIALISING); if (!ignoreIntent) { // Single top activities can be launched from stack and there may be a new intent provided with onNewIntent() call. // In this case need to wait till onResume to get the latest intent. Bypass this if isForceSession_ is true. if (intentState_ != INTENT_STATE.READY && !isForceSessionEnabled()) { request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.INTENT_PENDING_WAIT_LOCK); } if (checkInstallReferrer_ && request instanceof ServerRequestRegisterInstall && !InstallListener.unreportedReferrerAvailable) { request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.INSTALL_REFERRER_FETCH_WAIT_LOCK); new InstallListener().captureInstallReferrer(context_, playStoreReferrerFetchTime, this); } } if (isGAParamsFetchInProgress_) { request.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.GAID_FETCH_WAIT_LOCK); } if (!requestQueue_.containsInitRequest()) { insertRequestAtFront(request); processNextQueueItem(); } } /* * Register app init without any wait on intents or other referring params. * This will not be getting any params from the intent */ void registerAppInitWithoutIntent() { ServerRequestInitSession request = getInstallOrOpenRequest(null); registerAppInit(request, true); } private ServerRequestInitSession getInstallOrOpenRequest(BranchReferralInitListener callback) { ServerRequestInitSession request; if (hasUser()) { // If there is user this is open request = new ServerRequestRegisterOpen(context_, callback); } else { // If no user this is an Install request = new ServerRequestRegisterInstall(context_, callback, InstallListener.getInstallationID()); } return request; } void onIntentReady(@NonNull Activity activity) { setIntentState(Branch.INTENT_STATE.READY); requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.INTENT_PENDING_WAIT_LOCK); boolean grabIntentParams = activity.getIntent() != null && getInitState() != Branch.SESSION_STATE.INITIALISED; if (grabIntentParams) { Uri intentData = activity.getIntent().getData(); readAndStripParam(intentData, activity); // Check for cookie based matching only if Tracking is enabled if (!isTrackingDisabled() && cookieBasedMatchDomain_ != null && prefHelper_.getBranchKey() != null && !prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { if (isGAParamsFetchInProgress_) { // Wait for GAID to Available performCookieBasedStrongMatchingOnGAIDAvailable = true; } else { performCookieBasedStrongMatch(); } } else { processNextQueueItem(); } } else { processNextQueueItem(); } } private void performCookieBasedStrongMatch() { if (!trackingController.isTrackingDisabled()) { Activity currentActivity = null; Context context = getApplicationContext(); if (context != null) { requestQueue_.setStrongMatchWaitLock(); BranchStrongMatchHelper.getInstance().checkForStrongMatch(context, cookieBasedMatchDomain_, deviceInfo_, prefHelper_, new BranchStrongMatchHelper.StrongMatchCheckEvents() { @Override public void onStrongMatchCheckFinished() { requestQueue_.unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK.STRONG_MATCH_PENDING_WAIT_LOCK); processNextQueueItem(); } }); } } } /** * Handles execution of a new request other than open or install. * Checks for the session initialisation and adds a install/Open request in front of this request * if the request need session to execute. * * @param req The {@link ServerRequest} to execute */ public void handleNewRequest(ServerRequest req) { // If Tracking is disabled fail all messages with ERR_BRANCH_TRACKING_DISABLED if (trackingController.isTrackingDisabled() && !req.prepareExecuteWithoutTracking()) { req.reportTrackingDisabledError(); return; } //If not initialised put an open or install request in front of this request(only if this needs session) if (initState_ != SESSION_STATE.INITIALISED && !(req instanceof ServerRequestInitSession)) { if ((req instanceof ServerRequestLogout)) { req.handleFailure(BranchError.ERR_NO_SESSION, ""); PrefHelper.Debug("Branch is not initialized, cannot logout"); return; } if ((req instanceof ServerRequestRegisterClose)) { PrefHelper.Debug("Branch is not initialized, cannot close session"); return; } if (requestNeedsSession(req)) { req.addProcessWaitLock(ServerRequest.PROCESS_WAIT_LOCK.SDK_INIT_WAIT_LOCK); } } if (!(req instanceof ServerRequestPing)) { requestQueue_.enqueue(req); req.onRequestQueued(); } processNextQueueItem(); } /** * Notify Branch when network is available in order to process the next request in the queue. */ public void notifyNetworkAvailable() { ServerRequest req = new ServerRequestPing(context_); handleNewRequest(req); } private void setActivityLifeCycleObserver(Application application) { try { activityLifeCycleObserver = new BranchActivityLifecycleObserver(); /* Set an observer for activity life cycle events. */ application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver); application.registerActivityLifecycleCallbacks(activityLifeCycleObserver); isActivityLifeCycleCallbackRegistered_ = true; } catch (NoSuchMethodError | NoClassDefFoundError Ex) { isActivityLifeCycleCallbackRegistered_ = false; isAutoSessionMode_ = false; /* LifeCycleEvents are available only from API level 14. */ PrefHelper.Debug(new BranchError("", BranchError.ERR_API_LVL_14_NEEDED).getMessage()); } } private boolean checkIntentForSessionRestart(Intent intent) { boolean isRestartSessionRequested = false; if (intent != null) { boolean forceSessionIntentKeyPresent = intent.getBooleanExtra(Defines.IntentKeys.ForceNewBranchSession.getKey(), false); boolean hasBranchLink = intent.getStringExtra(Defines.IntentKeys.BranchURI.getKey()) != null; boolean branchLinkNotConsumedYet = !intent.getBooleanExtra(Defines.IntentKeys.BranchLinkUsed.getKey(), false); isRestartSessionRequested = forceSessionIntentKeyPresent || (hasBranchLink && branchLinkNotConsumedYet); } return isRestartSessionRequested; } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralInitListener}, defining a single method that takes a list of params in * {@link JSONObject} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONObject * @see BranchError */ public interface BranchReferralInitListener { void onInitFinished(JSONObject referringParams, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchUniversalReferralInitListener}, defining a single method that provides * {@link BranchUniversalObject}, {@link LinkProperties} and an error message of {@link BranchError} format that will be * returned on failure of the request response. * In case of an error the value for {@link BranchUniversalObject} and {@link LinkProperties} are set to null.</p> * * @see BranchUniversalObject * @see LinkProperties * @see BranchError */ public interface BranchUniversalReferralInitListener { void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralStateChangedListener}, defining a single method that takes a value of * {@link Boolean} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see Boolean * @see BranchError */ public interface BranchReferralStateChangedListener { void onStateChanged(boolean changed, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkCreateListener}, defining a single method that takes a URL * {@link String} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see String * @see BranchError */ public interface BranchLinkCreateListener { void onLinkCreate(String url, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkShareListener}, defining methods to listen for link sharing status.</p> */ public interface BranchLinkShareListener { /** * <p> Callback method to update when share link dialog is launched.</p> */ void onShareLinkDialogLaunched(); /** * <p> Callback method to update when sharing dialog is dismissed.</p> */ void onShareLinkDialogDismissed(); /** * <p> Callback method to update the sharing status. Called on sharing completed or on error.</p> * * @param sharedLink The link shared to the channel. * @param sharedChannel Channel selected for sharing. * @param error A {@link BranchError} to update errors, if there is any. */ void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error); /** * <p>Called when user select a channel for sharing a deep link. * Branch will create a deep link for the selected channel and share with it after calling this * method. On sharing complete, status is updated by onLinkShareResponse() callback. Consider * having a sharing in progress UI if you wish to prevent user activity in the window between selecting a channel * and sharing complete.</p> * * @param channelName Name of the selected application to share the link. An empty string is returned if unable to resolve selected client name. */ void onChannelSelected(String channelName); } /** * <p>An extended version of {@link BranchLinkShareListener} with callback that supports updating link data or properties after user select a channel to share * This will provide the extended callback {@link #onChannelSelected(String, BranchUniversalObject, LinkProperties)} only when sharing a link using Branch Universal Object.</p> */ public interface ExtendedBranchLinkShareListener extends BranchLinkShareListener { /** * <p> * Called when user select a channel for sharing a deep link. * This method allows modifying the link data and properties by providing the params {@link BranchUniversalObject} and {@link LinkProperties} * </p> * * @param channelName The name of the channel user selected for sharing a link * @param buo {@link BranchUniversalObject} BUO used for sharing link for updating any params * @param linkProperties {@link LinkProperties} associated with the sharing link for updating the properties * @return Return {@code true} to create link with any updates added to the data ({@link BranchUniversalObject}) or to the properties ({@link LinkProperties}). * Return {@code false} otherwise. */ boolean onChannelSelected(String channelName, BranchUniversalObject buo, LinkProperties linkProperties); } /** * <p>An interface class for customizing sharing properties with selected channel.</p> */ public interface IChannelProperties { /** * @param channel The name of the channel selected for sharing. * @return {@link String} with value for the message title for sharing the link with the selected channel */ String getSharingTitleForChannel(String channel); /** * @param channel The name of the channel selected for sharing. * @return {@link String} with value for the message body for sharing the link with the selected channel */ String getSharingMessageForChannel(String channel); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchListResponseListener}, defining a single method that takes a list of * {@link JSONArray} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONArray * @see BranchError */ public interface BranchListResponseListener { void onReceivingResponse(JSONArray list, BranchError error); } /** * <p> * Callback interface for listening logout status * </p> */ public interface LogoutStatusListener { /** * Called on finishing the the logout process * * @param loggedOut A {@link Boolean} which is set to true if logout succeeded * @param error An instance of {@link BranchError} to notify any error occurred during logout. * A null value is set if logout succeeded. */ void onLogoutFinished(boolean loggedOut, BranchError error); } /** * <p>enum containing the sort options for return of credit history.</p> */ public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } /** * Async Task to create a shorlink for synchronous methods */ private class GetShortLinkTask extends AsyncTask<ServerRequest, Void, ServerResponse> { @Override protected ServerResponse doInBackground(ServerRequest... serverRequests) { return branchRemoteInterface_.make_restful_post(serverRequests[0].getPost(), prefHelper_.getAPIBaseUrl() + Defines.RequestPath.GetURL.getPath(), Defines.RequestPath.GetURL.getPath(), prefHelper_.getBranchKey()); } } /** * Asynchronous task handling execution of server requests. Execute the network task on background * thread and request are executed in sequential manner. Handles the request execution in * Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are * published in the main thread. */ private class BranchPostTask extends BranchAsyncTask<Void, Void, ServerResponse> { ServerRequest thisReq_; public BranchPostTask(ServerRequest request) { thisReq_ = request; } @Override protected void onPreExecute() { super.onPreExecute(); thisReq_.onPreExecute(); thisReq_.doFinalUpdateOnMainThread(); } @Override protected ServerResponse doInBackground(Void... voids) { // update queue wait time addExtraInstrumentationData(thisReq_.getRequestPath() + "-" + Defines.Jsonkey.Queue_Wait_Time.getKey(), String.valueOf(thisReq_.getQueueWaitTime())); thisReq_.doFinalUpdateOnBackgroundThread(); if (isTrackingDisabled() && thisReq_.prepareExecuteWithoutTracking() == false) { return new ServerResponse(thisReq_.getRequestPath(), BranchError.ERR_BRANCH_TRACKING_DISABLED); } if (thisReq_.isGetRequest()) { return branchRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getGetParams(), thisReq_.getRequestPath(), prefHelper_.getBranchKey()); } else { return branchRemoteInterface_.make_restful_post(thisReq_.getPostWithInstrumentationValues(instrumentationExtraData_), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), prefHelper_.getBranchKey()); } } @Override protected void onPostExecute(ServerResponse serverResponse) { super.onPostExecute(serverResponse); if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); hasNetwork_ = true; if (serverResponse.getStatusCode() == BranchError.ERR_BRANCH_TRACKING_DISABLED) { thisReq_.reportTrackingDisabledError(); requestQueue_.remove(thisReq_); } else { //If the request is not succeeded if (status != 200) { //If failed request is an initialisation request then mark session not initialised if (thisReq_ instanceof ServerRequestInitSession) { setInitState(SESSION_STATE.UNINITIALISED); } // On a bad request or in canse of a conflict notify with call back and remove the request. if (status == 400 || status == 409) { requestQueue_.remove(thisReq_); if (thisReq_ instanceof ServerRequestCreateUrl) { ((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError(); } else { PrefHelper.LogAlways("Branch API Error: Conflicting resource error code from API"); handleFailure(0, status); } } //On Network error or Branch is down fail all the pending requests in the queue except //for request which need to be replayed on failure. else { hasNetwork_ = false; //Collect all request from the queue which need to be failed. ArrayList<ServerRequest> requestToFail = new ArrayList<>(); for (int i = 0; i < requestQueue_.getSize(); i++) { requestToFail.add(requestQueue_.peekAt(i)); } //Remove the requests from the request queue first for (ServerRequest req : requestToFail) { if (req == null || !req.shouldRetryOnFail()) { // Should remove any nullified request object also from queue requestQueue_.remove(req); } } // Then, set the network count to zero, indicating that requests can be started again. networkCount_ = 0; //Finally call the request callback with the error. for (ServerRequest req : requestToFail) { if (req != null) { req.handleFailure(status, serverResponse.getFailReason()); //If request need to be replayed, no need for the callbacks if (req.shouldRetryOnFail()) req.clearCallbacks(); } } } } // If the request succeeded else { hasNetwork_ = true; //On create new url cache the url. if (thisReq_ instanceof ServerRequestCreateUrl) { if (serverResponse.getObject() != null) { final String url = serverResponse.getObject().getString("url"); // cache the link linkCache_.put(((ServerRequestCreateUrl) thisReq_).getLinkPost(), url); } } //On Logout clear the link cache and all pending requests else if (thisReq_ instanceof ServerRequestLogout) { linkCache_.clear(); requestQueue_.clear(); } requestQueue_.dequeue(); // If this request changes a session update the session-id to queued requests. if (thisReq_ instanceof ServerRequestInitSession || thisReq_ instanceof ServerRequestIdentifyUserRequest) { // Immediately set session and Identity and update the pending request with the params JSONObject respJson = serverResponse.getObject(); if (respJson != null) { boolean updateRequestsInQueue = false; if (!isTrackingDisabled()) { // Update PII data only if tracking is disabled if (respJson.has(Defines.Jsonkey.SessionID.getKey())) { prefHelper_.setSessionID(respJson.getString(Defines.Jsonkey.SessionID.getKey())); updateRequestsInQueue = true; } if (respJson.has(Defines.Jsonkey.IdentityID.getKey())) { String new_Identity_Id = respJson.getString(Defines.Jsonkey.IdentityID.getKey()); if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) { //On setting a new identity Id clear the link cache linkCache_.clear(); prefHelper_.setIdentityID(respJson.getString(Defines.Jsonkey.IdentityID.getKey())); updateRequestsInQueue = true; } } if (respJson.has(Defines.Jsonkey.DeviceFingerprintID.getKey())) { prefHelper_.setDeviceFingerPrintID(respJson.getString(Defines.Jsonkey.DeviceFingerprintID.getKey())); updateRequestsInQueue = true; } } if (updateRequestsInQueue) { updateAllRequestsInQueue(); } if (thisReq_ instanceof ServerRequestInitSession) { setInitState(SESSION_STATE.INITIALISED); thisReq_.onRequestSucceeded(serverResponse, branchReferral_); if (!((ServerRequestInitSession) thisReq_).handleBranchViewIfAvailable((serverResponse))) { checkForAutoDeepLinkConfiguration(); } // Count down the latch holding getLatestReferringParamsSync if (getLatestReferringParamsLatch != null) { getLatestReferringParamsLatch.countDown(); } // Count down the latch holding getFirstReferringParamsSync if (getFirstReferringParamsLatch != null) { getFirstReferringParamsLatch.countDown(); } } else { // For setting identity just call only request succeeded thisReq_.onRequestSucceeded(serverResponse, branchReferral_); } } } else { //Publish success to listeners thisReq_.onRequestSucceeded(serverResponse, branchReferral_); } } } networkCount_ = 0; if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) { processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } /** * <p>Checks if an activity is launched by Branch auto deep link feature. Branch launches activitie configured for auto deep link on seeing matching keys. * Keys for auto deep linking should be specified to each activity as a meta data in manifest.</p> * Configure your activity in your manifest to enable auto deep linking as follows * <!-- * <activity android:name=".YourActivity"> * <meta-data android:name="io.branch.sdk.auto_link" android:value="DeepLinkKey1","DeepLinkKey2" /> * </activity> * --> * * @param activity Instance of activity to check if launched on auto deep link. * @return A {Boolean} value whose value is true if this activity is launched by Branch auto deeplink feature. */ public static boolean isAutoDeepLinkLaunch(Activity activity) { return (activity.getIntent().getStringExtra(AUTO_DEEP_LINKED) != null); } private void checkForAutoDeepLinkConfiguration() { JSONObject latestParams = getLatestReferringParams(); String deepLinkActivity = null; try { //Check if the application is launched by clicking a Branch link. if (!latestParams.has(Defines.Jsonkey.Clicked_Branch_Link.getKey()) || !latestParams.getBoolean(Defines.Jsonkey.Clicked_Branch_Link.getKey())) { return; } if (latestParams.length() > 0) { // Check if auto deep link is disabled. ApplicationInfo appInfo = context_.getPackageManager().getApplicationInfo(context_.getPackageName(), PackageManager.GET_META_DATA); if (appInfo.metaData != null && appInfo.metaData.getBoolean(AUTO_DEEP_LINK_DISABLE, false)) { return; } PackageInfo info = context_.getPackageManager().getPackageInfo(context_.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA); ActivityInfo[] activityInfos = info.activities; int deepLinkActivityReqCode = DEF_AUTO_DEEP_LINK_REQ_CODE; if (activityInfos != null) { for (ActivityInfo activityInfo : activityInfos) { if (activityInfo != null && activityInfo.metaData != null && (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null || activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null)) { if (checkForAutoDeepLinkKeys(latestParams, activityInfo) || checkForAutoDeepLinkPath(latestParams, activityInfo)) { deepLinkActivity = activityInfo.name; deepLinkActivityReqCode = activityInfo.metaData.getInt(AUTO_DEEP_LINK_REQ_CODE, DEF_AUTO_DEEP_LINK_REQ_CODE); break; } } } } if (deepLinkActivity != null && getCurrentActivity() != null) { Activity currentActivity = getCurrentActivity(); Intent intent = new Intent(currentActivity, Class.forName(deepLinkActivity)); intent.putExtra(AUTO_DEEP_LINKED, "true"); // Put the raw JSON params as extra in case need to get the deep link params as JSON String intent.putExtra(Defines.Jsonkey.ReferringData.getKey(), latestParams.toString()); // Add individual parameters in the data Iterator<?> keys = latestParams.keys(); while (keys.hasNext()) { String key = (String) keys.next(); intent.putExtra(key, latestParams.getString(key)); } currentActivity.startActivityForResult(intent, deepLinkActivityReqCode); } else { // This case should not happen. Adding a safe handling for any corner case PrefHelper.Debug("No activity reference to launch deep linked activity"); } } } catch (final PackageManager.NameNotFoundException e) { PrefHelper.Debug("Warning: Please make sure Activity names set for auto deep link are correct!"); } catch (ClassNotFoundException e) { PrefHelper.Debug("Warning: Please make sure Activity names set for auto deep link are correct! Error while looking for activity " + deepLinkActivity); } catch (Exception ignore) { // Can get TransactionTooLarge Exception here if the Application info exceeds 1mb binder data limit. Usually results with manifest merge from SDKs } } private boolean checkForAutoDeepLinkKeys(JSONObject params, ActivityInfo activityInfo) { if (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null) { String[] activityLinkKeys = activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY).split(","); for (String activityLinkKey : activityLinkKeys) { if (params.has(activityLinkKey)) { return true; } } } return false; } private boolean checkForAutoDeepLinkPath(JSONObject params, ActivityInfo activityInfo) { String deepLinkPath = null; try { if (params.has(Defines.Jsonkey.AndroidDeepLinkPath.getKey())) { deepLinkPath = params.getString(Defines.Jsonkey.AndroidDeepLinkPath.getKey()); } else if (params.has(Defines.Jsonkey.DeepLinkPath.getKey())) { deepLinkPath = params.getString(Defines.Jsonkey.DeepLinkPath.getKey()); } } catch (JSONException ignored) { } if (activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null && deepLinkPath != null) { String[] activityLinkPaths = activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH).split(","); for (String activityLinkPath : activityLinkPaths) { if (pathMatch(activityLinkPath.trim(), deepLinkPath)) { return true; } } } return false; } private boolean pathMatch(String templatePath, String path) { boolean matched = true; String[] pathSegmentsTemplate = templatePath.split("\\?")[0].split("/"); String[] pathSegmentsTarget = path.split("\\?")[0].split("/"); if (pathSegmentsTemplate.length != pathSegmentsTarget.length) { return false; } for (int i = 0; i < pathSegmentsTemplate.length && i < pathSegmentsTarget.length; i++) { String pathSegmentTemplate = pathSegmentsTemplate[i]; String pathSegmentTarget = pathSegmentsTarget[i]; if (!pathSegmentTemplate.equals(pathSegmentTarget) && !pathSegmentTemplate.contains("*")) { matched = false; break; } } return matched; } public static void enableSimulateInstalls() { isSimulatingInstalls_ = true; } public static void disableSimulateInstalls() { isSimulatingInstalls_ = false; } static boolean isSimulatingInstalls() { return isSimulatingInstalls_; } /** * Enable Logging, independent of Debug Mode. */ public static void enableLogging() { PrefHelper.enableLogging(true); } /** * Disable Logging, independent of Debug Mode. */ public static void disableLogging() { PrefHelper.enableLogging(false); } public static void enableForcedSession() { ignoreIntent_ = true; } public static void disableForcedSession() { ignoreIntent_ = false; } /** * Returns true if forced session is enabled * * @return {@link Boolean} with value true to enable forced session */ public static boolean isForceSessionEnabled() { return ignoreIntent_; } public static void enableBypassCurrentActivityIntentState() { bypassCurrentActivityIntentState_ = true; } public static boolean bypassCurrentActivityIntentState() { return bypassCurrentActivityIntentState_; } void setIsReferrable(boolean isReferrable) { if (isReferrable) { prefHelper_.setIsReferrable(); } else { prefHelper_.clearIsReferrable(); } } boolean isReferrable() { return prefHelper_.getIsReferrable() == 1; } public void registerView(BranchUniversalObject branchUniversalObject, BranchUniversalObject.RegisterViewStatusListener callback) { if (context_ != null) { new BranchEvent(BRANCH_STANDARD_EVENT.VIEW_ITEM) .addContentItems(branchUniversalObject) .logEvent(context_); } } /** * Update the extra instrumentation data provided to Branch * * @param instrumentationData A {@link HashMap} with key value pairs for instrumentation data. */ public void addExtraInstrumentationData(HashMap<String, String> instrumentationData) { instrumentationExtraData_.putAll(instrumentationData); } /** * Update the extra instrumentation data provided to Branch * * @param key A {@link String} Value for instrumentation data key * @param value A {@link String} Value for instrumentation data value */ public void addExtraInstrumentationData(String key, String value) { instrumentationExtraData_.put(key, value); } @Override public void onBranchViewVisible(String action, String branchViewID) { //No Implementation on purpose } @Override public void onBranchViewAccepted(String action, String branchViewID) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } @Override public void onBranchViewCancelled(String action, String branchViewID) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } @Override public void onBranchViewError(int errorCode, String errorMsg, String action) { if (ServerRequestInitSession.isInitSessionAction(action)) { checkForAutoDeepLinkConfiguration(); } } /** * Interface for defining optional Branch view behaviour for Activities */ public interface IBranchViewControl { /** * Defines if an activity is interested to show Branch views or not. * By default activities are considered as Branch view enabled. In case of activities which are not interested to show a Branch view (Splash screen for example) * should implement this and return false. The pending Branch view will be shown with the very next Branch view enabled activity * * @return A {@link Boolean} whose value is true if the activity don't want to show any Branch view. */ boolean skipBranchViewsOnThisActivity(); } /** * Checks if this is an Instant app instance * * @param context Current {@link Context} * @return {@code true} if current application is an instance of instant app */ public static boolean isInstantApp(@NonNull Context context) { return InstantAppUtil.isInstantApp(context); } /** * Method shows play store install prompt for the full app. Thi passes the referrer to the installed application. The same deep link params as the instant app are provided to the * full app up on Branch#initSession() * * @param activity Current activity * @param requestCode Request code for the activity to receive the result * @return {@code true} if install prompt is shown to user */ public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode) { String installReferrerString = ""; if (Branch.getInstance() != null) { JSONObject latestReferringParams = Branch.getInstance().getLatestReferringParams(); String referringLinkKey = "~" + Defines.Jsonkey.ReferringLink.getKey(); if (latestReferringParams != null && latestReferringParams.has(referringLinkKey)) { String referringLink = ""; try { referringLink = latestReferringParams.getString(referringLinkKey); // Considering the case that url may contain query params with `=` and `&` with it and may cause issue when parsing play store referrer referringLink = URLEncoder.encode(referringLink, "UTF-8"); } catch (JSONException | UnsupportedEncodingException e) { e.printStackTrace(); } if (!TextUtils.isEmpty(referringLink)) { installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + Defines.Jsonkey.ReferringLink.getKey() + "=" + referringLink; } } } return InstantAppUtil.doShowInstallPrompt(activity, requestCode, installReferrerString); } /** * Method shows play store install prompt for the full app. Use this method only if you have custom parameters to pass to the full app using referrer else use * {@link #showInstallPrompt(Activity, int)} * * @param activity Current activity * @param requestCode Request code for the activity to receive the result * @param referrer Any custom referrer string to pass to full app (must be of format "referrer_key1=referrer_value1%26referrer_key2=referrer_value2") * @return {@code true} if install prompt is shown to user */ public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @Nullable String referrer) { String installReferrerString = Defines.Jsonkey.IsFullAppConv.getKey() + "=true&" + referrer; return InstantAppUtil.doShowInstallPrompt(activity, requestCode, installReferrerString); } /** * Method shows play store install prompt for the full app. Use this method only if you want the full app to receive a custom {@link BranchUniversalObject} to do deferred deep link. * Please see {@link #showInstallPrompt(Activity, int)} * NOTE : * This method will do a synchronous generation of Branch short link for the BUO. So please consider calling this method on non UI thread * Please make sure your instant app and full ap are using same Branch key in order for the deferred deep link working * * @param activity Current activity * @param requestCode Request code for the activity to receive the result * @param buo {@link BranchUniversalObject} to pass to the full app up on install * @return {@code true} if install prompt is shown to user */ public static boolean showInstallPrompt(@NonNull Activity activity, int requestCode, @NonNull BranchUniversalObject buo) { if (buo != null) { String shortUrl = buo.getShortUrl(activity, new LinkProperties()); String installReferrerString = Defines.Jsonkey.ReferringLink.getKey() + "=" + shortUrl; if (!TextUtils.isEmpty(installReferrerString)) { return showInstallPrompt(activity, requestCode, installReferrerString); } else { return showInstallPrompt(activity, requestCode, ""); } } return false; } private void extractSessionParamsForIDL(Uri data, Activity activity) { if (activity == null || activity.getIntent() == null) return; Intent intent = activity.getIntent(); // In case of a cold start by clicking app icon or bringing app to foreground Branch link click is always false. // todo investigate this, already consumed, yet enable IDL with no data try { if (data == null || isIntentParamsAlreadyConsumed(activity)) { // Considering the case of a deferred install. In this case the app behaves like a cold // start but still Branch can do probabilistic match. So skipping instant deep link feature // until first Branch open happens. if (!prefHelper_.getInstallParams().equals(PrefHelper.NO_STRING_VALUE)) { JSONObject nonLinkClickJson = new JSONObject(); nonLinkClickJson.put(Defines.Jsonkey.IsFirstSession.getKey(), false); prefHelper_.setSessionParams(nonLinkClickJson.toString()); isInstantDeepLinkPossible = true; } } else if (!TextUtils.isEmpty(intent.getStringExtra(Defines.IntentKeys.BranchData.getKey()))) { // If not cold start, check the intent data to see if there are deep link params String rawBranchData = intent.getStringExtra(Defines.IntentKeys.BranchData.getKey()); if (rawBranchData != null) { // Make sure the data received is complete and in correct format JSONObject branchDataJson = new JSONObject(rawBranchData); branchDataJson.put(Defines.Jsonkey.Clicked_Branch_Link.getKey(), true); prefHelper_.setSessionParams(branchDataJson.toString()); isInstantDeepLinkPossible = true; } // Remove Branch data from the intent once used intent.removeExtra(Defines.IntentKeys.BranchData.getKey()); activity.setIntent(intent); } else if (data.isHierarchical() && Boolean.valueOf(data.getQueryParameter(Defines.Jsonkey.Instant.getKey()))) { // If instant key is true in query params, use them for instant deep linking JSONObject branchDataJson = new JSONObject(); for (String key : data.getQueryParameterNames()) { branchDataJson.put(key, data.getQueryParameter(key)); } branchDataJson.put(Defines.Jsonkey.Clicked_Branch_Link.getKey(), true); prefHelper_.setSessionParams(branchDataJson.toString()); isInstantDeepLinkPossible = true; } } catch (JSONException ignored) {} } private void extractAppLink(Uri data, Activity activity) { if (data == null || activity == null) return; String scheme = data.getScheme(); Intent intent = activity.getIntent(); if (scheme != null && intent != null && (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) && !TextUtils.isEmpty(data.getHost()) && !isIntentParamsAlreadyConsumed(activity)) { String strippedUrl = UniversalResourceAnalyser.getInstance(context_).getStrippedURL(data.toString()); if (data.toString().equalsIgnoreCase(strippedUrl)) { // Send app links only if URL is not skipped. prefHelper_.setAppLink(data.toString()); } intent.putExtra(Defines.IntentKeys.BranchLinkUsed.getKey(), true); activity.setIntent(intent); } } private boolean extractClickID(Uri data, Activity activity) { try { if (data == null || !data.isHierarchical()) return false; String linkClickID = data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()); if (linkClickID == null) return false; prefHelper_.setLinkClickIdentifier(linkClickID); String paramString = "link_click_id=" + linkClickID; String uriString = data.toString(); if (paramString.equals(data.getQuery())) { paramString = "\\?" + paramString; } else if ((uriString.length() - paramString.length()) == uriString.indexOf(paramString)) { paramString = "&" + paramString; } else { paramString = paramString + "&"; } Uri uriWithoutClickID = Uri.parse(uriString.replaceFirst(paramString, "")); activity.getIntent().setData(uriWithoutClickID); activity.getIntent().putExtra(Defines.IntentKeys.BranchLinkUsed.getKey(), true); return true; } catch (Exception ignore) { return false; } } private boolean extractBranchLinkFromIntentExtra(Activity activity) { //Check for any push identifier in case app is launched by a push notification try { if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) { if (!isIntentParamsAlreadyConsumed(activity)) { Object object = activity.getIntent().getExtras().get(Defines.IntentKeys.BranchURI.getKey()); String branchLink = null; if (object instanceof String) { branchLink = (String) object; } else if (object instanceof Uri) { Uri uri = (Uri) object; branchLink = uri.toString(); } if (!TextUtils.isEmpty(branchLink)) { prefHelper_.setPushIdentifier(branchLink); Intent thisIntent = activity.getIntent(); thisIntent.putExtra(Defines.IntentKeys.BranchLinkUsed.getKey(), true); activity.setIntent(thisIntent); return true; } } } } catch (Exception ignore) { } return false; } private void extractExternalUriAndIntentExtras(Uri data, Activity activity) { try { if (!isIntentParamsAlreadyConsumed(activity)) { String strippedUrl = UniversalResourceAnalyser.getInstance(context_).getStrippedURL(data.toString()); prefHelper_.setExternalIntentUri(strippedUrl); if (strippedUrl.equals(data.toString())) { Bundle bundle = activity.getIntent().getExtras(); Set<String> extraKeys = bundle.keySet(); if (extraKeys.isEmpty()) return; JSONObject extrasJson = new JSONObject(); for (String key : EXTERNAL_INTENT_EXTRA_KEY_WHITE_LIST) { if (extraKeys.contains(key)) { extrasJson.put(key, bundle.get(key)); } } if (extrasJson.length() > 0) { prefHelper_.setExternalIntentExtra(extrasJson.toString()); } } } } catch (Exception ignore) { } } Activity getCurrentActivity() { if (currentActivityReference_ == null) return null; return currentActivityReference_.get(); } public static class InitSessionBuilder { private BranchReferralInitListener callback; private Uri uri; private Boolean isReferrable; private Boolean ignoreIntent; private InitSessionBuilder(Activity activity) { Branch.getInstance().currentActivityReference_ = new WeakReference<>(activity); } /** * <p> Add callback to Branch initialization to retrieve referring params attached to the * Branch link via the dashboard. User eventually decides how to use the referring params but * they are primarily meant to be used for navigating to specific content within the app.</p> * * @param callback A {@link BranchUniversalReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. */ public InitSessionBuilder withCallback(BranchUniversalReferralInitListener callback) { this.callback = new BranchUniversalReferralInitWrapper(callback); return this; } /** * <p> Add callback to Branch initialization to retrieve referring params attached to the * Branch link via the dashboard. User eventually decides how to use the referring params but * they are primarily meant to be used for navigating to specific content within the app.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. */ public InitSessionBuilder withCallback(BranchReferralInitListener callback) { this.callback = callback; return this; } /** * <p> Specify a {@link Uri} variable containing the details of the source link that led to * this initialisation action.</p> * * @param uri A {@link Uri} variable from the intent. */ public InitSessionBuilder withData(Uri uri) { this.uri = uri; return this; } /** * <p> Specify whether the initialisation can count as a referrable action. </p> * * @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance * should be considered as potentially referrable or not. By default, a session is only referrable * if it is a fresh install resulting from clicking on a Branch link. Overriding this gives you * control of who is referrable. */ public InitSessionBuilder isReferrable(boolean isReferrable) { this.isReferrable = isReferrable; return this; } /** * <p> Session initialization is expected to begin in onStart rather than onResume to prevent * multiple initializations during the a single app session. However, by default, Branch actually * waits until onResume to start session initialization, so as to ensure that the latest intent * data is available. Set this flag to start session without delay.</p> * * @param ignoreIntent a {@link Boolean} indicating if intent is needed before session initialization . */ public InitSessionBuilder ignoreIntent(boolean ignoreIntent) { this.ignoreIntent = ignoreIntent; return this; } /** * <p>Initialises a session with the Branch API, registers the passed in Activity, callback * and configuration variables, then initializes session.</p> */ public void init() { Branch b = Branch.getInstance(); if (b == null) { PrefHelper.LogAlways("Branch is not setup properly, make sure to call getAutoInstance" + " in your application class or declare BranchApp in your manifest."); return; } if (ignoreIntent != null) { ignoreIntent_ = ignoreIntent; } if (isReferrable != null) { b.setIsReferrable(isReferrable); } if (uri != null) { b.readAndStripParam(uri, b.getCurrentActivity()); } b.initUserSessionInternal(callback, b.getCurrentActivity()); } /** * <p> Re-Initialize a session. Call from Activity.onNewIntent(). * This solves a very specific use case, whereas the app is already in the foreground and a new * intent with a Uri is delivered to the foregrounded activity. * * Note that the Uri can also be stored as an extra in the field under the key `IntentKeys.BranchURI.getKey()` (i.e. "branch"). * * Note also, that the since the method is expected to be called from Activity.onNewIntent(), * the implementation assumes the intent will be non-null and will contain a Branch link in * either the URI or in the the extra.</p> * */ public void reInit() { Branch b = Branch.getInstance(); Activity activity = b.getCurrentActivity(); if (activity == null) return; Intent intent = activity.getIntent(); if (intent != null) { // Re-Initializing with a Uri indicates that we want to fetch the data before we return. Uri uri = intent.getData(); String pushNotifUrl = intent.getStringExtra(Defines.IntentKeys.BranchURI.getKey()); if (uri == null && !TextUtils.isEmpty(pushNotifUrl)) { uri = Uri.parse(pushNotifUrl); } if (uri != null) { // Let's indicate that the app was initialized with this uri. b.prefHelper_.setExternalIntentUri(uri.toString()); // We need to set the AndroidAppLinkURL as well b.prefHelper_.setAppLink(uri.toString()); // Now, actually initialize the new session. b.readAndStripParam(uri, activity); } else { PrefHelper.Debug("Warning! Session reinitialization cannot be performed. Intent must" + "contain either a valid URI or an extra where key = \"branch\" and value = \"Branch link\" "); } b.initializeSession(callback, false); } else { PrefHelper.Debug("Warning! Session reinitialization cannot be performed when intent is null."); } } } // * @param activity The calling {@link Activity} for context. public static InitSessionBuilder sessionBuilder(Activity activity) { return new InitSessionBuilder(activity); } /** * <p> Legacy class for building a share link dialog. Use {@link BranchShareSheetBuilder} instead. </p> */ @Deprecated public static class ShareLinkBuilder extends BranchShareSheetBuilder { @Deprecated public ShareLinkBuilder(Activity activity, JSONObject parameters) { super(activity, parameters); } @Deprecated public ShareLinkBuilder(Activity activity, BranchShortLinkBuilder shortLinkBuilder) { super(activity, shortLinkBuilder); } public ShareLinkBuilder setMessage(String message) { super.setMessage(message); return this; } public ShareLinkBuilder setSubject(String subject) { super.setSubject(subject); return this; } public ShareLinkBuilder addTag(String tag) { super.addTag(tag); return this; } public ShareLinkBuilder addTags(ArrayList<String> tags) { super.addTags(tags); return this; } public ShareLinkBuilder setFeature(String feature) { super.setFeature(feature); return this; } public ShareLinkBuilder setStage(String stage) { super.setStage(stage); return this; } public ShareLinkBuilder setCallback(BranchLinkShareListener callback) { super.setCallback(callback); return this; } public ShareLinkBuilder setChannelProperties(IChannelProperties channelPropertiesCallback) { super.setChannelProperties(channelPropertiesCallback); return this; } public ShareLinkBuilder addPreferredSharingOption(SharingHelper.SHARE_WITH preferredOption) { super.addPreferredSharingOption(preferredOption); return this; } public ShareLinkBuilder addPreferredSharingOptions(ArrayList<SharingHelper.SHARE_WITH> preferredOptions) { super.addPreferredSharingOptions(preferredOptions); return this; } public ShareLinkBuilder addParam(String key, String value) { super.addParam(key, value); return this; } public ShareLinkBuilder setDefaultURL(String url) { super.setDefaultURL(url); return this; } public ShareLinkBuilder setMoreOptionStyle(Drawable icon, String label) { super.setMoreOptionStyle(icon, label); return this; } public ShareLinkBuilder setMoreOptionStyle(int drawableIconID, int stringLabelID) { super.setMoreOptionStyle(drawableIconID, stringLabelID); return this; } public ShareLinkBuilder setCopyUrlStyle(Drawable icon, String label, String message) { super.setCopyUrlStyle(icon, label, message); return this; } public ShareLinkBuilder setCopyUrlStyle(int drawableIconID, int stringLabelID, int stringMessageID) { super.setCopyUrlStyle(drawableIconID, stringLabelID, stringMessageID); return this; } public ShareLinkBuilder setAlias(String alias) { super.setAlias(alias); return this; } public ShareLinkBuilder setMatchDuration(int matchDuration) { super.setMatchDuration(matchDuration); return this; } public ShareLinkBuilder setAsFullWidthStyle(boolean setFullWidthStyle) { super.setAsFullWidthStyle(setFullWidthStyle); return this; } public ShareLinkBuilder setDialogThemeResourceID(@StyleRes int styleResourceID) { super.setDialogThemeResourceID(styleResourceID); return this; } public ShareLinkBuilder setDividerHeight(int height) { super.setDividerHeight(height); return this; } public ShareLinkBuilder setSharingTitle(String title) { super.setSharingTitle(title); return this; } public ShareLinkBuilder setSharingTitle(View titleView) { super.setSharingTitle(titleView); return this; } public ShareLinkBuilder setIconSize(int iconSize) { super.setIconSize(iconSize); return this; } public ShareLinkBuilder excludeFromShareSheet(@NonNull String packageName) { super.excludeFromShareSheet(packageName); return this; } public ShareLinkBuilder excludeFromShareSheet(@NonNull String[] packageName) { super.excludeFromShareSheet(packageName); return this; } public ShareLinkBuilder excludeFromShareSheet(@NonNull List<String> packageNames) { super.excludeFromShareSheet(packageNames); return this; } public ShareLinkBuilder includeInShareSheet(@NonNull String packageName) { super.includeInShareSheet(packageName); return this; } public ShareLinkBuilder includeInShareSheet(@NonNull String[] packageName) { super.includeInShareSheet(packageName); return this; } public ShareLinkBuilder includeInShareSheet(@NonNull List<String> packageNames) { super.includeInShareSheet(packageNames); return this; } } }
package de.teiesti.postie.recipients; import de.teiesti.postie.Postman; import de.teiesti.postie.Recipient; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Mailbox<Letter> implements Recipient<Letter> { private final BlockingQueue<Letter> inbox = new LinkedBlockingQueue<>(); @Override public void accept(Letter letter, Postman postman) { inbox.add(letter); } public Letter receive() throws InterruptedException { return inbox.take(); } public boolean hasLetter() { return !inbox.isEmpty(); } }