code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.xyz.practice.jdbc.databasemetadata; import java.io.Serializable; public class Procedure implements Serializable { private static final long serialVersionUID = -4039205106133212013L; /** * procedure catalog (may be null) */ private String procedureCat; /** * procedure schema (may be null) */ private String procedureSchem; /** * procedure name */ private String procedureName; /** * explanatory comment on the procedure */ private String remarks; /** * kind of procedure: * procedureResultUnknown - Cannot determine if a return value will be returned * procedureNoResult - Does not return a return value * procedureReturnsResult - Returns a return value */ private short procedureType; /** * The name which uniquely identifies this procedure within its schema. */ private String specificName; String getProcedureCat() { return procedureCat; } void setProcedureCat( String procedureCat ) { this.procedureCat = procedureCat; } String getProcedureSchem() { return procedureSchem; } void setProcedureSchem( String procedureSchem ) { this.procedureSchem = procedureSchem; } String getProcedureName() { return procedureName; } void setProcedureName( String procedureName ) { this.procedureName = procedureName; } String getRemarks() { return remarks; } void setRemarks( String remarks ) { this.remarks = remarks; } short getProcedureType() { return procedureType; } void setProcedureType( short procedureType ) { this.procedureType = procedureType; } String getSpecificName() { return specificName; } void setSpecificName( String specificName ) { this.specificName = specificName; } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.List; public class DatabaseMetaDataAccess { private DatabaseMetaData dmd; public DatabaseMetaDataAccess( DatabaseMetaData dmd ) { this.dmd = dmd; } public Database getDatabase() throws SQLException { Database db = new Database(); return db; } public List< ReferenceKey > getCrossReference( String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable ) throws SQLException { List< ReferenceKey > referenceKeys = Converter.convertReferenceKeys( dmd.getCrossReference( parentCatalog, parentSchema, parentTable, foreignCatalog, foreignSchema, foreignTable ) ); return referenceKeys; } public List< ColumnPrivilege > getColumnPrivileges( String catalog, String schema, String table, String columnNamePattern ) throws SQLException { List< ColumnPrivilege > columnPrivileges = Converter.convertColumnPrivileges( dmd.getColumnPrivileges( catalog, schema, table, columnNamePattern ) ); return columnPrivileges; } public List< ClientInfoProperty > getClientInfoProperties() throws SQLException { List< ClientInfoProperty > clientInfoPropertys = Converter.convertClientInfoProperties( dmd.getClientInfoProperties() ); return clientInfoPropertys; } public List< ProcedureColumn > getProcedureColumns( String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern ) throws SQLException { List< ProcedureColumn > procedureColumns = Converter.convertProcedureColumns( dmd.getProcedureColumns( catalog, schemaPattern, procedureNamePattern, columnNamePattern ) ); return procedureColumns; } public List< Procedure > getProcedures( String catalog, String schemaPattern, String procedureNamePattern ) throws SQLException { List< Procedure > procedures = Converter.convertProcedures( dmd.getProcedures( catalog, schemaPattern, procedureNamePattern ) ); return procedures; } public List< ReferenceKey > getExportedKeys( String catalog, String schema, String table ) throws SQLException { List< ReferenceKey > referenceKeys = Converter.convertReferenceKeys( dmd.getExportedKeys( catalog, schema, table ) ); return referenceKeys; } public List< ReferenceKey > getImportedKeys( String catalog, String schema, String table ) throws SQLException { List< ReferenceKey > referenceKeys = Converter.convertReferenceKeys( dmd.getImportedKeys( catalog, schema, table ) ); return referenceKeys; } public List< FunctionColumn > getFunctionColumns( String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern ) throws SQLException { List< FunctionColumn > functionColumns = Converter.convertFunctionColumns( dmd.getFunctionColumns( catalog, schemaPattern, functionNamePattern, columnNamePattern ) ); return functionColumns; } public List< Function > getFunctions( String catalog, String schemaPattern, String functionNamePattern ) throws SQLException { List< Function > functions = Converter.convertFunctions( dmd.getFunctions( catalog, schemaPattern, functionNamePattern ) ); return functions; } public List< Attribute > getAttributes( String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern ) throws SQLException { List< Attribute > attributes = Converter.convertAttributes( dmd.getAttributes( catalog, schemaPattern, typeNamePattern, attributeNamePattern ) ); return attributes; } public List< PrimaryKey > getPrimaryKeys( String table ) throws SQLException { return getPrimaryKeys( null, null, table ); } public List< PrimaryKey > getPrimaryKeys( String catalog, String schema, String table ) throws SQLException { List< PrimaryKey > primaryKeys = Converter.convertPrimaryKeys( dmd.getPrimaryKeys( catalog, schema, table ) ); return primaryKeys; } public List< Schema > getSchemas() throws SQLException { List< Schema > schemas = Converter.convertSchemas( dmd.getSchemas() ); return schemas; } public List< Schema > getSchemas( String catalog, String schemaPattern ) throws SQLException { List< Schema > schemas = Converter.convertSchemas( dmd.getSchemas( catalog, schemaPattern ) ); return schemas; } public List< Catalog > getCatalogs() throws SQLException { List< Catalog > catalogs = Converter.convertCatalogs( dmd.getCatalogs() ); return catalogs; } public List< Column > getColumns( String tableNamePattern ) throws SQLException { return getColumns( null, null, tableNamePattern, null ); } public List< Column > getColumns( String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern ) throws SQLException { List< Column > columns = Converter.convertColumns( dmd.getColumns( catalog, schemaPattern, tableNamePattern, columnNamePattern ) ); return columns; } public List< TableType > getTableTypes() throws SQLException { List< TableType > tableTypes = Converter.convertTableTypes( dmd.getTableTypes() ); return tableTypes; } public List< Table > getTables() throws SQLException { return getTables( null, null, null, null ); } public List< Table > getTables( String catalog, String schemaPattern, String tableNamePattern, String[] types ) throws SQLException { List< Table > tables = Converter.convertTables( dmd.getTables( catalog, schemaPattern, tableNamePattern, types ) ); return tables; } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.io.Serializable; public class Attribute implements Serializable { private static final long serialVersionUID = -5617701978805722911L; Attribute() { } /** * type catalog (may be null) */ private String typeCat; /** * type schema (may be null) */ private String typeSchem; /** * type name */ private String typeName; /** * attribute name */ private String attrName; /** * attribute type SQL type from java.sql.Types */ private int dataType; /** * Data source dependent type name. For a UDT, the type name is fully * qualified. For a REF, the type name is fully qualified and represents the * target type of the reference type. */ private String attrTypeName; /** * column size. For char or date types this is the maximum number of * characters; for numeric or decimal types this is precision. */ private int attrSize; /** * the number of fractional digits. Null is returned for data types where * DECIMAL_DIGITS is not applicable. */ private int decimalDigits; /** * Radix (typically either 10 or 2) */ private int numPrecRadix; /** * whether NULL is allowed attributeNoNulls - might not allow NULL values * attributeNullable - definitely allows NULL values * attributeNullableUnknown - nullability unknown */ private String remarks; /** * default value (may be null) */ private String attrDef; /** * for char types the maximum number of bytes in the column */ private int charOctetLength; /** * ISO rules are used to determine the nullability for a attribute. YES --- * if the attribute can include NULLs NO --- if the attribute cannot include * NULLs empty string --- if the nullability for the attribute is unknown */ private String isNullable; /** * catalog of table that is the scope of a reference attribute (null if * DATA_TYPE isn't REF) */ private String scopeCatalog; /** * schema of table that is the scope of a reference attribute (null if * DATA_TYPE isn't REF) */ private String scopeSchem; /** * table name that is the scope of a reference attribute (null if the * DATA_TYPE isn't REF) */ private String scopeTable; /** * source type of a distinct type or user-generated Ref type,SQL type from * java.sql.Types (null if DATA_TYPE isn't DISTINCT or user-generated REF) */ private short sourceDataType; String getTypeCat() { return typeCat; } void setTypeCat(String typeCat) { this.typeCat = typeCat; } String getTypeSchem() { return typeSchem; } void setTypeSchem(String typeSchem) { this.typeSchem = typeSchem; } String getTypeName() { return typeName; } void setTypeName(String typeName) { this.typeName = typeName; } String getAttrName() { return attrName; } void setAttrName(String attrName) { this.attrName = attrName; } int getDataType() { return dataType; } void setDataType(int dataType) { this.dataType = dataType; } String getAttrTypeName() { return attrTypeName; } void setAttrTypeName(String attrTypeName) { this.attrTypeName = attrTypeName; } int getAttrSize() { return attrSize; } void setAttrSize(int attrSize) { this.attrSize = attrSize; } int getDecimalDigits() { return decimalDigits; } void setDecimalDigits(int decimalDigits) { this.decimalDigits = decimalDigits; } int getNumPrecRadix() { return numPrecRadix; } void setNumPrecRadix(int numPrecRadix) { this.numPrecRadix = numPrecRadix; } String getRemarks() { return remarks; } void setRemarks(String remarks) { this.remarks = remarks; } String getAttrDef() { return attrDef; } void setAttrDef(String attrDef) { this.attrDef = attrDef; } int getCharOctetLength() { return charOctetLength; } void setCharOctetLength(int charOctetLength) { this.charOctetLength = charOctetLength; } String getIsNullable() { return isNullable; } void setIsNullable(String isNullable) { this.isNullable = isNullable; } String getScopeCatalog() { return scopeCatalog; } void setScopeCatalog(String scopeCatalog) { this.scopeCatalog = scopeCatalog; } String getScopeSchem() { return scopeSchem; } void setScopeSchem(String scopeSchem) { this.scopeSchem = scopeSchem; } String getScopeTable() { return scopeTable; } void setScopeTable(String scopeTable) { this.scopeTable = scopeTable; } short getSourceDataType() { return sourceDataType; } void setSourceDataType(short sourceDataType) { this.sourceDataType = sourceDataType; } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.io.Serializable; public class ReferenceKey implements Serializable { private static final long serialVersionUID = -6410614779914708218L; ReferenceKey() { } /** * primary key table catalog (may be null) */ private String pktableCat; /** * primary key table schema (may be null) */ private String pktableSchem; /** * primary key table name */ private String pktableName; /** * primary key column name */ private String pkcolumnName; /** * foreign key table catalog (may be null) being exported (may be null) */ private String fktableCat; /** * foreign key table schema (may be null) being exported (may be null) */ private String fktableSchema; /** * foreign key table name being exported */ private String fktableName; /** * foreign key column name being exported */ private String fkcolumnName; /** * sequence number within foreign key( a value of 1 represents the first * column of the foreign key, a value of 2 would represent the second column * within the foreign key). */ private short keySeq; /** * What happens to foreign key when primary is updated: importedNoAction - * do not allow update of primary key if it has been imported * importedKeyCascade - change imported key to agree with primary key update * importedKeySetNull - change imported key to NULL if its primary key has * been updated importedKeySetDefault - change imported key to default * values if its primary key has been updated importedKeyRestrict - same as * importedKeyNoAction (for ODBC 2.x compatibility) */ private short updateRule; /** * What happens to the foreign key when primary is deleted. * importedKeyNoAction - do not allow delete of primary key if it has been * imported importedKeyCascade - delete rows that import a deleted key * importedKeySetNull - change imported key to NULL if its primary key has * been deleted importedKeyRestrict - same as importedKeyNoAction (for ODBC * 2.x compatibility) importedKeySetDefault - change imported key to default * if its primary key has been deleted */ private short deleteRule; /** * foreign key name (may be null) */ private String fkName; /** * primary key name (may be null) */ private String pkName; /** * can the evaluation of foreign key constraints be deferred until commit * importedKeyInitiallyDeferred - see SQL92 for definition * importedKeyInitiallyImmediate - see SQL92 for definition * importedKeyNotDeferrable - see SQL92 for definition */ private short deferrability; String getPktableCat() { return pktableCat; } void setPktableCat(String pktableCat) { this.pktableCat = pktableCat; } String getPktableSchem() { return pktableSchem; } void setPktableSchem(String pktableSchem) { this.pktableSchem = pktableSchem; } String getPktableName() { return pktableName; } void setPktableName(String pktableName) { this.pktableName = pktableName; } String getPkcolumnName() { return pkcolumnName; } void setPkcolumnName(String pkcolumnName) { this.pkcolumnName = pkcolumnName; } String getFktableCat() { return fktableCat; } void setFktableCat(String fktableCat) { this.fktableCat = fktableCat; } String getFktableSchema() { return fktableSchema; } void setFktableSchema(String fktableSchema) { this.fktableSchema = fktableSchema; } String getFktableName() { return fktableName; } void setFktableName(String fktableName) { this.fktableName = fktableName; } String getFkcolumnName() { return fkcolumnName; } void setFkcolumnName(String fkcolumnName) { this.fkcolumnName = fkcolumnName; } short getKeySeq() { return keySeq; } void setKeySeq(short keySeq) { this.keySeq = keySeq; } short getUpdateRule() { return updateRule; } void setUpdateRule(short updateRule) { this.updateRule = updateRule; } short getDeleteRule() { return deleteRule; } void setDeleteRule(short deleteRule) { this.deleteRule = deleteRule; } String getFkName() { return fkName; } void setFkName(String fkName) { this.fkName = fkName; } String getPkName() { return pkName; } void setPkName(String pkName) { this.pkName = pkName; } short getDeferrability() { return deferrability; } void setDeferrability(short deferrability) { this.deferrability = deferrability; } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.io.Serializable; public class PrimaryKey implements Serializable { private static final long serialVersionUID = 5318323189946727916L; PrimaryKey() {} /** * table catalog (may be null) */ private String tableCat; /** * table schema (may be null) */ private String tableSchem; /** * table name */ private String tableName; /** * column name */ private String columnName; /** * sequence number within primary key( a value of 1 represents the first column of the primary key, a value of 2 would represent the second column within the primary key). */ private short keySeq; /** * primary key name (may be null) */ private String pkName; String getTableCat() { return tableCat; } void setTableCat( String tableCat ) { this.tableCat = tableCat; } String getTableSchem() { return tableSchem; } void setTableSchem( String tableSchem ) { this.tableSchem = tableSchem; } String getTableName() { return tableName; } void setTableName( String tableName ) { this.tableName = tableName; } String getColumnName() { return columnName; } void setColumnName( String columnName ) { this.columnName = columnName; } short getKeySeq() { return keySeq; } void setKeySeq( short keySeq ) { this.keySeq = keySeq; } String getPkName() { return pkName; } void setPkName( String pkName ) { this.pkName = pkName; } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.io.Serializable; public class Catalog implements Serializable { private static final long serialVersionUID = 2377152708691352775L; Catalog(String tableCat) { this.tableCat = tableCat; } private String tableCat; String getTableCat() { return tableCat; } void setTableCat(String tableCat) { this.tableCat = tableCat; } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { static { try { Class.forName( "oracle.jdbc.OracleDriver" ); // Class.forName( "com.mysql.jdbc.Driver" ); } catch ( ClassNotFoundException e ) { e.printStackTrace(); } } public static Connection getConnection( String dbUrl, String username, String password ) { try { return DriverManager.getConnection( dbUrl, username, password ); } catch ( SQLException e ) { e.printStackTrace(); return null; } } public static void close( Connection connection ) { try { connection.close(); } catch ( SQLException e ) { e.printStackTrace(); } } public static void close( Statement statement ) { try { statement.close(); } catch ( SQLException e ) { e.printStackTrace(); } } public static void close( ResultSet resultSet ) { try { resultSet.close(); } catch ( SQLException e ) { e.printStackTrace(); } } }
Java
package com.xyz.practice.jdbc.databasemetadata; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; class Converter { static List<ColumnPrivilege> convertColumnPrivileges( ResultSet rs ) throws SQLException { if ( rs != null ) { List<ColumnPrivilege> columnPrivileges = new ArrayList<ColumnPrivilege>(); while ( rs.next() ) { ColumnPrivilege columnPrivilege = new ColumnPrivilege(); columnPrivilege.setColumnName( rs.getString( "COLUMN_NAME" ) ); columnPrivilege.setGrantee( rs.getString( "GRANTEE" ) ); columnPrivilege.setGrantor( rs.getString( "GRANTOR" ) ); columnPrivilege.setIsGrantable( rs.getString( "IS_GRANTABLE" ) ); columnPrivilege.setPrivilege( rs.getString( "PRIVILEGE" ) ); columnPrivilege.setTableCat( rs.getString( "TABLE_CAT" ) ); columnPrivilege.setTableName( rs.getString( "TABLE_NAME" ) ); columnPrivilege.setTableSchem( rs.getString( "TABLE_SCHEM" ) ); columnPrivileges.add( columnPrivilege ); } return columnPrivileges; } return null; } static List<ClientInfoProperty> convertClientInfoProperties( ResultSet rs ) throws SQLException { if ( rs != null ) { List<ClientInfoProperty> clientInfoPropertys = new ArrayList<ClientInfoProperty>(); while ( rs.next() ) { ClientInfoProperty clientInfoProperty = new ClientInfoProperty(); clientInfoProperty.setDefaultValue( rs.getString( "DEFAULT_VALUE" ) ); clientInfoProperty.setDescription( rs.getString( "DESCRIPTION" ) ); clientInfoProperty.setMaxLen( rs.getInt( "MAX_LEN" ) ); clientInfoProperty.setName( rs.getString( "NAME" ) ); clientInfoPropertys.add( clientInfoProperty ); } return clientInfoPropertys; } return null; } static List<ProcedureColumn> convertProcedureColumns( ResultSet rs ) throws SQLException { if ( rs != null ) { List<ProcedureColumn> procedureColumns = new ArrayList<ProcedureColumn>(); while ( rs.next() ) { ProcedureColumn procedureColumn = new ProcedureColumn(); procedureColumn.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) ); procedureColumn.setColumnDef( rs.getString( "COLUMN_DEF" ) ); procedureColumn.setColumnName( rs.getString( "COLUMN_NAME" ) ); procedureColumn.setColumnType( rs.getShort( "COLUMN_TYPE" ) ); procedureColumn.setDataType( rs.getInt( "DATA_TYPE" ) ); procedureColumn.setIsNullable( rs.getString( "IS_NULLABLE" ) ); procedureColumn.setLength( rs.getInt( "LENGTH" ) ); procedureColumn.setNullable( rs.getShort( "NULLABLE" ) ); procedureColumn.setOrdinalPosition( rs.getInt( "ORDINAL_POSITION" ) ); procedureColumn.setPrecision( rs.getInt( "PRECISION" ) ); procedureColumn.setProcedureCat( rs.getString( "PROCEDURE_CAT" ) ); procedureColumn.setProcedureName( rs.getString( "PROCEDURE_NAME" ) ); procedureColumn.setProcedureSchem( rs.getString( "PROCEDURE_SCHEM" ) ); procedureColumn.setRadix( rs.getShort( "RADIX" ) ); procedureColumn.setRemarks( rs.getString( "REMARKS" ) ); procedureColumn.setScale( rs.getShort( "SCALE" ) ); procedureColumn.setSpecificName( rs.getString( "SPECIFIC_NAME" ) ); procedureColumn.setSqlDataType( rs.getInt( "SQL_DATA_TYPE" ) ); procedureColumn.setSqlDatetimeSub( rs.getInt( "SQL_DATETIME_SUB" ) ); procedureColumn.setTypeName( rs.getString( "TYPE_NAME" ) ); procedureColumns.add( procedureColumn ); } return procedureColumns; } return null; } static List<Procedure> convertProcedures( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Procedure> procedures = new ArrayList<Procedure>(); while ( rs.next() ) { Procedure procedure = new Procedure(); procedure.setProcedureCat( rs.getString( "PROCEDURE_CAT" ) ); procedure.setProcedureName( rs.getString( "PROCEDURE_NAME" ) ); procedure.setProcedureSchem( rs.getString( "PROCEDURE_SCHEM" ) ); procedure.setProcedureType( rs.getShort( "PROCEDURE_TYPE" ) ); procedure.setRemarks( rs.getString( "REMARKS" ) ); procedure.setSpecificName( rs.getString( "SPECIFIC_NAME" ) ); procedures.add( procedure ); } return procedures; } return null; } static List<FunctionColumn> convertFunctionColumns( ResultSet rs ) throws SQLException { if ( rs != null ) { List<FunctionColumn> functionColumns = new ArrayList<FunctionColumn>(); while ( rs.next() ) { FunctionColumn functionColumn = new FunctionColumn(); functionColumn.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) ); functionColumn.setColumnName( rs.getString( "COLUMN_NAME" ) ); functionColumn.setColumnType( rs.getShort( "COLUMN_TYPE" ) ); functionColumn.setDataType( rs.getInt( "DATA_TYPE" ) ); functionColumn.setFunctionCat( rs.getString( "FUNCTION_CAT" ) ); functionColumn.setFunctionName( rs.getString( "FUNCTION_NAME" ) ); functionColumn.setFunctionSchem( rs.getString( "FUNCTION_SCHEM" ) ); functionColumn.setIsNullable( rs.getString( "IS_NULLABLE" ) ); functionColumn.setLength( rs.getInt( "LENGTH" ) ); functionColumn.setNullable( rs.getShort( "NULLABLE" ) ); functionColumn.setOrdinalPosition( rs.getInt( "ORDINAL_POSITION" ) ); functionColumn.setPrecision( rs.getInt( "PRECISION" ) ); functionColumn.setRadix( rs.getShort( "RADIX" ) ); functionColumn.setRemarks( rs.getString( "REMARKS" ) ); functionColumn.setScale( rs.getShort( "SCALE" ) ); functionColumn.setSpecificName( rs.getString( "SPECIFIC_NAME" ) ); functionColumn.setTypeName( rs.getString( "TYPE_NAME" ) ); functionColumns.add( functionColumn ); } return functionColumns; } return null; } static List<ReferenceKey> convertReferenceKeys( ResultSet rs ) throws SQLException { if ( rs != null ) { List<ReferenceKey> referenceKeys = new ArrayList<ReferenceKey>(); while ( rs.next() ) { ReferenceKey referenceKey = new ReferenceKey(); referenceKey.setDeferrability( rs.getShort( "DEFERRABILITY" ) ); referenceKey.setDeleteRule( rs.getShort( "DELETE_RULE" ) ); referenceKey.setFkcolumnName( rs.getString( "FKCOLUMN_NAME" ) ); referenceKey.setFkName( rs.getString( "FK_NAME" ) ); referenceKey.setFktableCat( rs.getString( "FKTABLE_CAT" ) ); referenceKey.setFktableName( rs.getString( "FKTABLE_NAME" ) ); referenceKey.setFktableSchema( rs.getString( "FKTABLE_SCHEM" ) ); referenceKey.setKeySeq( rs.getShort( "KEY_SEQ" ) ); referenceKey.setPkcolumnName( rs.getString( "PKCOLUMN_NAME" ) ); referenceKey.setPkName( rs.getString( "PK_NAME" ) ); referenceKey.setPktableCat( rs.getString( "PKTABLE_CAT" ) ); referenceKey.setPktableName( rs.getString( "PKTABLE_NAME" ) ); referenceKey.setPktableSchem( rs.getString( "PKTABLE_SCHEM" ) ); referenceKey.setUpdateRule( rs.getShort( "UPDATE_RULE" ) ); referenceKeys.add( referenceKey ); } return referenceKeys; } return null; } static List<Function> convertFunctions( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Function> functions = new ArrayList<Function>(); while ( rs.next() ) { Function function = new Function(); function.setFunctionCat( rs.getString( "FUNCTION_CAT" ) ); function.setFunctionName( rs.getString( "FUNCTION_NAME" ) ); function.setFunctionSchema( rs.getString( "FUNCTION_SCHEM" ) ); function.setFunctionType( rs.getShort( "FUNCTION_TYPE" ) ); function.setRemarks( rs.getString( "REMARKS" ) ); function.setSpecificName( rs.getString( "SPECIFIC_NAME" ) ); functions.add( function ); } return functions; } return null; } static List<Attribute> convertAttributes( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Attribute> attributes = new ArrayList<Attribute>(); while ( rs.next() ) { Attribute attribute = new Attribute(); attribute.setAttrDef( rs.getString( "ATTR_DEF" ) ); attribute.setAttrName( rs.getString( "ATTR_NAME" ) ); attribute.setAttrSize( rs.getInt( "ATTR_SIZE" ) ); attribute.setAttrTypeName( rs.getString( "ATTR_TYPE_NAME" ) ); attribute.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) ); attribute.setDataType( rs.getInt( "DATA_TYPE" ) ); attribute.setDecimalDigits( rs.getInt( "DECIMAL_DIGITS" ) ); attribute.setIsNullable( rs.getString( "IS_NULLABLE" ) ); attribute.setNumPrecRadix( rs.getInt( "NUM_PREC_RADIX" ) ); attribute.setRemarks( rs.getString( "REMARKS" ) ); attribute.setScopeCatalog( rs.getString( "SCOPE_CATALOG" ) ); attribute.setScopeSchem( rs.getString( "SCOPE_SCHEMA" ) ); attribute.setScopeTable( rs.getString( "SCOPE_TABLE" ) ); attribute.setSourceDataType( rs.getShort( "SOURCE_DATA_TYPE" ) ); attribute.setTypeCat( rs.getString( "TYPE_CAT" ) ); attribute.setTypeName( rs.getString( "TYPE_NAME" ) ); attribute.setTypeSchem( rs.getString( "TYPE_SCHEM" ) ); attributes.add( attribute ); } return attributes; } return null; } static List<PrimaryKey> convertPrimaryKeys( ResultSet rs ) throws SQLException { if ( rs != null ) { List<PrimaryKey> primaryKeys = new ArrayList<PrimaryKey>(); while ( rs.next() ) { PrimaryKey primaryKey = new PrimaryKey(); primaryKey.setColumnName( rs.getString( "COLUMN_NAME" ) ); primaryKey.setKeySeq( rs.getShort( "KEY_SEQ" ) ); primaryKey.setPkName( rs.getString( "PK_NAME" ) ); primaryKey.setTableCat( rs.getString( "TABLE_CAT" ) ); primaryKey.setTableName( rs.getString( "TABLE_NAME" ) ); primaryKey.setTableSchem( rs.getString( "TABLE_SCHEM" ) ); primaryKeys.add( primaryKey ); } return primaryKeys; } return null; } static List<Schema> convertSchemas( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Schema> schemas = new ArrayList<Schema>(); while ( rs.next() ) { Schema schema = new Schema(); schema.setTableSchem( rs.getString( "TABLE_SCHEM" ) ); // schema.setTableCatalog( rs.getString( "TABLE_CATALOG" ) ); schemas.add( schema ); } return schemas; } return null; } static List<Catalog> convertCatalogs( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Catalog> catalogs = new ArrayList<Catalog>(); while ( rs.next() ) { catalogs.add( new Catalog( rs.getString( "TABLE_CAT" ) ) ); } return catalogs; } return null; } static List<Table> convertTables( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Table> tables = new ArrayList<Table>(); while ( rs.next() ) { Table table = new Table(); // table.setRefGeneration( rs.getString( "REF_GENERATION" ) ); // MySQL not supported table.setRemarks( rs.getString( "REMARKS" ) ); // table.setSelfReferencingColName( rs.getString( // "SELF_REFERENCING_COL_NAME" ) ); MySQL not supported table.setTableCat( rs.getString( "TABLE_CAT" ) ); table.setTableName( rs.getString( "TABLE_NAME" ) ); table.setTableSchem( rs.getString( "TABLE_SCHEM" ) ); table.setTableType( new TableType( rs.getString( "TABLE_TYPE" ) ) ); // table.setTypeCat( rs.getString( "TYPE_CAT" ) ); MySQL not // supported // table.setTypeName( rs.getString( "TYPE_NAME" ) ); MySQL not // supported // table.setTypeSchem( rs.getString( "TYPE_SCHEM" ) ); MySQL not // supported tables.add( table ); } return tables; } return null; } static List<TableType> convertTableTypes( ResultSet rs ) throws SQLException { if ( rs != null ) { List<TableType> tableTypes = new ArrayList<TableType>(); while ( rs.next() ) { tableTypes.add( new TableType( rs.getString( "TABLE_TYPE" ) ) ); } return tableTypes; } return null; } static List<Column> convertColumns( ResultSet rs ) throws SQLException { if ( rs != null ) { List<Column> columns = new ArrayList<Column>(); while ( rs.next() ) { Column column = new Column(); column.setCharOctetLength( rs.getInt( "CHAR_OCTET_LENGTH" ) ); column.setColumnDef( rs.getString( "COLUMN_DEF" ) ); column.setColumnName( rs.getString( "COLUMN_NAME" ) ); column.setColumnSize( rs.getInt( "COLUMN_SIZE" ) ); column.setDataType( rs.getInt( "DATA_TYPE" ) ); column.setDecimalDigits( rs.getInt( "DECIMAL_DIGITS" ) ); column.setIsAutoincrement( rs.getString( "IS_AUTOINCREMENT" ) ); column.setIsNullable( rs.getString( "IS_NULLABLE" ) ); column.setNullable( rs.getInt( "NULLABLE" ) ); column.setNumPrecRadix( rs.getInt( "NUM_PREC_RADIX" ) ); column.setOriginalPosition( rs.getInt( "ORDINAL_POSITION" ) ); column.setRemarks( rs.getString( "REMARKS" ) ); // column.setScopeCatlog( rs.getString( "SCOPE_CATLOG" ) ); // MySQL not supported column.setScopeSchema( rs.getString( "SCOPE_SCHEMA" ) ); column.setScopeTable( rs.getString( "SCOPE_TABLE" ) ); column.setSourceDataType( rs.getShort( "SOURCE_DATA_TYPE" ) ); column.setTableCat( rs.getString( "TABLE_CAT" ) ); column.setTableName( rs.getString( "TABLE_NAME" ) ); column.setTableSchem( rs.getString( "TABLE_SCHEM" ) ); column.setTypeName( rs.getString( "TYPE_NAME" ) ); columns.add( column ); } return columns; } return null; } }
Java
package com.xyz.practice.reflection; import java.lang.reflect.Method; public class ReflectionUtil { public static Object invokeMethod( Object bean, String methodName ) throws Exception { return invokeMethod( bean, methodName, null, null ); } public static <T> Object invokeMethod( Object bean, String methodName, Object[] methodParameters ) throws Exception { return invokeMethod( bean, methodName, getClasses( methodParameters ), methodParameters ); } public static <T> Object invokeMethod( Object bean, String methodName, Class<? extends Object>[] classes, Object[] methodParameters ) throws Exception { Method method = bean.getClass().getDeclaredMethod( methodName, classes ); return method.invoke( bean, methodParameters ); } public static Class<? extends Object>[] getClasses( Object... objects ) { if ( objects != null && objects.length > 0 ) { Class<? extends Object>[] classes = new Class<?>[objects.length]; for ( int i = 0; i < objects.length; i++ ) { classes[i] = objects[i].getClass(); } return classes; } return null; } }
Java
package com.xyz.practice.digester.test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Foo { private String name; private List<Bar> bars = new ArrayList<Bar>(); public void addBar( Bar bar ) { bars.add( bar ); } public Bar findBar( int id ) { for ( Bar bar : bars ) { if (bar.getId() == id) { return bar; } } return null; } public Iterator<Bar> getBars() { return bars.iterator(); } public String getName() { return name; } public void setName( String name ) { this.name = name; } }
Java
package com.xyz.practice.digester.test; public class Bar { private int id; private String title; public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getTitle() { return title; } public void setTitle( String title ) { this.title = title; } }
Java
package com.xyz.practice.jdbc.test; public class Database { /** * Retrieves whether the current user can call all the procedures returned by the method getProcedures. */ private boolean allProceduresAreCallable; /** * Retrieves whether the current user can use all the tables returned by the method getTables in a SELECT statement. */ private boolean allTablesAreSelectable; /** * Retrieves whether a SQLException while autoCommit is true indicates that all open ResultSets are closed, even ones that are holdable. */ private boolean autoCommitFailureClosesAllResultSets; /** * Retrieves whether a data definition statement within a transaction forces the transaction to commit. */ private boolean dataDefinitionCausesTransactionCommit; /** * Retrieves whether this database ignores a data definition statement within a transaction. */ private boolean dataDefinitionIgnoredInTransactions; /** * Retrieves whether or not a visible row delete can be detected by calling the method ResultSet.rowDeleted. */ private boolean deletesAreDetected; /** * Retrieves whether the return value for the method getMaxRowSize includes the SQL data types LONGVARCHAR and LONGVARBINARY. */ private boolean doesMaxRowSizeIncludeBlobs; private int majorVersion; private int minorVersion; private String productName; private String productVersion; }
Java
package com.xyz.practice.jdbc.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private final static String db_url = ""; private final static String username = ""; private final static String password = ""; static { try { // Class.forName( "oracle.jdbc.OracleDriver" ); Class.forName( "com.mysql.jdbc.Driver" ); } catch ( ClassNotFoundException e ) { e.printStackTrace(); } } public static Connection getConnection() { return getConnection( db_url, username, password ); } public static Connection getConnection( String dbUrl, String username, String password ) { try { return DriverManager.getConnection( dbUrl, username, password ); } catch ( SQLException e ) { e.printStackTrace(); return null; } } public static void close( Connection connection ) { try { connection.close(); } catch ( SQLException e ) { e.printStackTrace(); } } public static void close( Statement statement ) { try { statement.close(); } catch ( SQLException e ) { e.printStackTrace(); } } public static void close( ResultSet resultSet ) { try { resultSet.close(); } catch ( SQLException e ) { e.printStackTrace(); } } public static void main( String[] args ) { Connection connection = getConnection(); close( connection ); } }
Java
package com.xyz.practice.classloader.test; public class SomeClass { private int id; private String name; public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String toString() { return this.id + " " + this.name; } }
Java
package com.xyz.practice.classloader.test; public class Sample { private Sample instance; public void setSample( Object instance ) { this.instance = ( Sample ) instance; System.out.println( "-------------- setSample method --------------" ); } public Sample getInstance() { return instance; } public void setInstance( Sample instance ) { this.instance = instance; } }
Java
package com.xyz.practice.classloader.test; public class MyClassLoader extends ClassLoader { @Override protected Class< ? > findClass( String className ) throws ClassNotFoundException { return this.loadClass( className ); } }
Java
package com.xyz.practice.classloader.test; public class ClassLoaderTree { /** * @param args */ public static void main( String[] args ) { ClassLoader loader = ClassLoaderTree.class.getClassLoader(); while ( loader != null ) { System.out.println( loader.toString() ); loader = loader.getParent(); } } }
Java
package com.xyz.practice.classloader.test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class FileSystemClassLoader extends ClassLoader { private String rootDir; public FileSystemClassLoader( String rootDir ) { this.rootDir = rootDir; } protected Class< ? > findClass( String name ) throws ClassNotFoundException { byte[] classData = getClassData( name ); if ( classData == null ) { throw new ClassNotFoundException(); } else { return defineClass( name, classData, 0, classData.length ); } } private byte[] getClassData( String className ) { String path = classNameToPath( className ); try { InputStream ins = new FileInputStream( path ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesNumRead = 0; while ( ( bytesNumRead = ins.read( buffer ) ) != -1 ) { baos.write( buffer, 0, bytesNumRead ); } return baos.toByteArray(); } catch ( IOException e ) { e.printStackTrace(); } return null; } private String classNameToPath( String className ) { return rootDir + File.separatorChar + className.replace( '.', File.separatorChar ) + ".class"; } }
Java
package com.xyz.practice.threadlocal.test; public class Session { public static ThreadLocal<UserInfo> userInfo = new ThreadLocal<UserInfo>() { @Override protected UserInfo initialValue() { return new UserInfo("Default"); } }; }
Java
package com.xyz.practice.threadlocal.test; public class UserInfo { public UserInfo( String name ) { this.name = name; } private String name; public String getName() { return name; } public void setName( String name ) { this.name = name; } }
Java
package com.xyz.practice.threadlocal.test; public class Request extends Thread { public void run() { System.out.println( "Thread :::: " + Session.userInfo.get().getName() ); } }
Java
package org.anddev.andengine.sensor.accelerometer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:58:38 - 10.03.2010 */ public interface IAccelerometerListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onAccelerometerChanged(final AccelerometerData pAccelerometerData); }
Java
package org.anddev.andengine.sensor.accelerometer; import java.util.Arrays; import org.anddev.andengine.sensor.BaseSensorData; import android.hardware.SensorManager; import android.view.Surface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:50:44 - 10.03.2010 */ public class AccelerometerData extends BaseSensorData { // =========================================================== // Constants // =========================================================== private static final IAxisSwap AXISSWAPS[] = new IAxisSwap[4]; static { AXISSWAPS[Surface.ROTATION_0] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = -pValues[SensorManager.DATA_X]; final float y = pValues[SensorManager.DATA_Y]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; AXISSWAPS[Surface.ROTATION_90] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = pValues[SensorManager.DATA_Y]; final float y = pValues[SensorManager.DATA_X]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; AXISSWAPS[Surface.ROTATION_180] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = pValues[SensorManager.DATA_X]; final float y = -pValues[SensorManager.DATA_Y]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; AXISSWAPS[Surface.ROTATION_270] = new IAxisSwap() { @Override public void swapAxis(final float[] pValues) { final float x = -pValues[SensorManager.DATA_Y]; final float y = -pValues[SensorManager.DATA_X]; pValues[SensorManager.DATA_X] = x; pValues[SensorManager.DATA_Y] = y; } }; } // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public AccelerometerData(final int pDisplayOrientation) { super(3, pDisplayOrientation); } // =========================================================== // Getter & Setter // =========================================================== public float getX() { return this.mValues[SensorManager.DATA_X]; } public float getY() { return this.mValues[SensorManager.DATA_Y]; } public float getZ() { return this.mValues[SensorManager.DATA_Z]; } public void setX(final float pX) { this.mValues[SensorManager.DATA_X] = pX; } public void setY(final float pY) { this.mValues[SensorManager.DATA_Y] = pY; } public void setZ(final float pZ) { this.mValues[SensorManager.DATA_Z] = pZ; } @Override public void setValues(final float[] pValues) { super.setValues(pValues); AccelerometerData.AXISSWAPS[this.mDisplayRotation].swapAxis(this.mValues); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Accelerometer: " + Arrays.toString(this.mValues); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== private static interface IAxisSwap { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void swapAxis(final float[] pValues); } }
Java
package org.anddev.andengine.sensor.accelerometer; import org.anddev.andengine.sensor.SensorDelay; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:10:34 - 31.10.2010 */ public class AccelerometerSensorOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== final SensorDelay mSensorDelay; // =========================================================== // Constructors // =========================================================== public AccelerometerSensorOptions(final SensorDelay pSensorDelay) { this.mSensorDelay = pSensorDelay; } // =========================================================== // Getter & Setter // =========================================================== public SensorDelay getSensorDelay() { return this.mSensorDelay; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.orientation; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:30:42 - 25.05.2010 */ public interface IOrientationListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onOrientationChanged(final OrientationData pOrientationData); }
Java
package org.anddev.andengine.sensor.orientation; import java.util.Arrays; import org.anddev.andengine.sensor.BaseSensorData; import org.anddev.andengine.util.constants.MathConstants; import android.hardware.SensorManager; import android.view.Surface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:30:33 - 25.05.2010 */ public class OrientationData extends BaseSensorData { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final float[] mAccelerometerValues = new float[3]; private final float[] mMagneticFieldValues = new float[3]; private final float[] mRotationMatrix = new float[16]; private int mMagneticFieldAccuracy; // =========================================================== // Constructors // =========================================================== public OrientationData(final int pDisplayRotation) { super(3, pDisplayRotation); } // =========================================================== // Getter & Setter // =========================================================== public float getRoll() { return super.mValues[SensorManager.DATA_Z]; } public float getPitch() { return super.mValues[SensorManager.DATA_Y]; } public float getYaw() { return super.mValues[SensorManager.DATA_X]; } @Override @Deprecated public void setValues(final float[] pValues) { super.setValues(pValues); } @Override @Deprecated public void setAccuracy(final int pAccuracy) { super.setAccuracy(pAccuracy); } public void setAccelerometerValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mAccelerometerValues, 0, pValues.length); this.updateOrientation(); } public void setMagneticFieldValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mMagneticFieldValues, 0, pValues.length); this.updateOrientation(); } private void updateOrientation() { SensorManager.getRotationMatrix(this.mRotationMatrix, null, this.mAccelerometerValues, this.mMagneticFieldValues); // TODO Use dont't use identical matrixes in remapCoordinateSystem, due to performance reasons. switch(this.mDisplayRotation) { case Surface.ROTATION_0: /* Nothing. */ break; case Surface.ROTATION_90: SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, this.mRotationMatrix); break; // case Surface.ROTATION_180: // SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); // break; // case Surface.ROTATION_270: // SensorManager.remapCoordinateSystem(this.mRotationMatrix, SensorManager.AXIS_?, SensorManager.AXIS_?, this.mRotationMatrix); // break; } final float[] values = this.mValues; SensorManager.getOrientation(this.mRotationMatrix, values); for(int i = values.length - 1; i >= 0; i--) { values[i] = values[i] * MathConstants.RAD_TO_DEG; } } public int getAccelerometerAccuracy() { return this.getAccuracy(); } public void setAccelerometerAccuracy(final int pAccelerometerAccuracy) { super.setAccuracy(pAccelerometerAccuracy); } public int getMagneticFieldAccuracy() { return this.mMagneticFieldAccuracy; } public void setMagneticFieldAccuracy(final int pMagneticFieldAccuracy) { this.mMagneticFieldAccuracy = pMagneticFieldAccuracy; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Orientation: " + Arrays.toString(this.mValues); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.orientation; import org.anddev.andengine.sensor.SensorDelay; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:12:36 - 31.10.2010 */ public class OrientationSensorOptions { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== final SensorDelay mSensorDelay; // =========================================================== // Constructors // =========================================================== public OrientationSensorOptions(final SensorDelay pSensorDelay) { this.mSensorDelay = pSensorDelay; } // =========================================================== // Getter & Setter // =========================================================== public SensorDelay getSensorDelay() { return this.mSensorDelay; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.location; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:39:23 - 31.10.2010 */ public interface ILocationListener { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * @see {@link LocationListener#onProviderEnabled(String)} */ public void onLocationProviderEnabled(); /** * @see {@link LocationListener#onLocationChanged(Location)} */ public void onLocationChanged(final Location pLocation); public void onLocationLost(); /** * @see {@link LocationListener#onProviderDisabled(String)} */ public void onLocationProviderDisabled(); /** * @see {@link LocationListener#onStatusChanged(String, int, android.os.Bundle)} */ public void onLocationProviderStatusChanged(final LocationProviderStatus pLocationProviderStatus, final Bundle pBundle); }
Java
package org.anddev.andengine.sensor.location; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:55:57 - 31.10.2010 */ public enum LocationProviderStatus { // =========================================================== // Elements // =========================================================== AVAILABLE, OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor.location; import org.anddev.andengine.util.constants.TimeConstants; import android.location.Criteria; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:02:12 - 31.10.2010 */ public class LocationSensorOptions extends Criteria { // =========================================================== // Constants // =========================================================== private static final long MINIMUMTRIGGERTIME_DEFAULT = 1 * TimeConstants.MILLISECONDSPERSECOND; private static final long MINIMUMTRIGGERDISTANCE_DEFAULT = 10; // =========================================================== // Fields // =========================================================== private boolean mEnabledOnly = true; private long mMinimumTriggerTime = MINIMUMTRIGGERTIME_DEFAULT; private long mMinimumTriggerDistance = MINIMUMTRIGGERDISTANCE_DEFAULT; // =========================================================== // Constructors // =========================================================== /** * @see {@link LocationSensorOptions#setAccuracy(int)}, * {@link LocationSensorOptions#setAltitudeRequired(boolean)}, * {@link LocationSensorOptions#setBearingRequired(boolean)}, * {@link LocationSensorOptions#setCostAllowed(boolean)}, * {@link LocationSensorOptions#setEnabledOnly(boolean)}, * {@link LocationSensorOptions#setMinimumTriggerDistance(long)}, * {@link LocationSensorOptions#setMinimumTriggerTime(long)}, * {@link LocationSensorOptions#setPowerRequirement(int)}, * {@link LocationSensorOptions#setSpeedRequired(boolean)}. */ public LocationSensorOptions() { } /** * @param pAccuracy * @param pAltitudeRequired * @param pBearingRequired * @param pCostAllowed * @param pPowerRequirement * @param pSpeedRequired * @param pEnabledOnly * @param pMinimumTriggerTime * @param pMinimumTriggerDistance */ public LocationSensorOptions(final int pAccuracy, final boolean pAltitudeRequired, final boolean pBearingRequired, final boolean pCostAllowed, final int pPowerRequirement, final boolean pSpeedRequired, final boolean pEnabledOnly, final long pMinimumTriggerTime, final long pMinimumTriggerDistance) { this.mEnabledOnly = pEnabledOnly; this.mMinimumTriggerTime = pMinimumTriggerTime; this.mMinimumTriggerDistance = pMinimumTriggerDistance; this.setAccuracy(pAccuracy); this.setAltitudeRequired(pAltitudeRequired); this.setBearingRequired(pBearingRequired); this.setCostAllowed(pCostAllowed); this.setPowerRequirement(pPowerRequirement); this.setSpeedRequired(pSpeedRequired); } // =========================================================== // Getter & Setter // =========================================================== public void setEnabledOnly(final boolean pEnabledOnly) { this.mEnabledOnly = pEnabledOnly; } public boolean isEnabledOnly() { return this.mEnabledOnly; } public long getMinimumTriggerTime() { return this.mMinimumTriggerTime; } public void setMinimumTriggerTime(final long pMinimumTriggerTime) { this.mMinimumTriggerTime = pMinimumTriggerTime; } public long getMinimumTriggerDistance() { return this.mMinimumTriggerDistance; } public void setMinimumTriggerDistance(final long pMinimumTriggerDistance) { this.mMinimumTriggerDistance = pMinimumTriggerDistance; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor; import java.util.Arrays; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:50:44 - 10.03.2010 */ public class BaseSensorData { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final float[] mValues; protected int mAccuracy; protected int mDisplayRotation; // =========================================================== // Constructors // =========================================================== public BaseSensorData(final int pValueCount, int pDisplayRotation) { this.mValues = new float[pValueCount]; this.mDisplayRotation = pDisplayRotation; } // =========================================================== // Getter & Setter // =========================================================== public float[] getValues() { return this.mValues; } public void setValues(final float[] pValues) { System.arraycopy(pValues, 0, this.mValues, 0, pValues.length); } public void setAccuracy(final int pAccuracy) { this.mAccuracy = pAccuracy; } public int getAccuracy() { return this.mAccuracy; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Values: " + Arrays.toString(this.mValues); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.sensor; import android.hardware.SensorManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:14:38 - 31.10.2010 */ public enum SensorDelay { // =========================================================== // Elements // =========================================================== NORMAL(SensorManager.SENSOR_DELAY_NORMAL), UI(SensorManager.SENSOR_DELAY_UI), GAME(SensorManager.SENSOR_DELAY_GAME), FASTEST(SensorManager.SENSOR_DELAY_FASTEST); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mDelay; // =========================================================== // Constructors // =========================================================== private SensorDelay(final int pDelay) { this.mDelay = pDelay; } // =========================================================== // Getter & Setter // =========================================================== public int getDelay() { return this.mDelay; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.level.util.constants; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:23:27 - 11.10.2010 */ public interface LevelConstants { // =========================================================== // Final Fields // =========================================================== public static final String TAG_LEVEL = "level"; public static final String TAG_LEVEL_ATTRIBUTE_NAME = "name"; public static final String TAG_LEVEL_ATTRIBUTE_UID = "uid"; public static final String TAG_LEVEL_ATTRIBUTE_WIDTH = "width"; public static final String TAG_LEVEL_ATTRIBUTE_HEIGHT = "height"; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.level; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.anddev.andengine.level.util.constants.LevelConstants; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import android.content.Context; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:16:19 - 11.10.2010 */ public class LevelLoader implements LevelConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private String mAssetBasePath; private IEntityLoader mDefaultEntityLoader; private final HashMap<String, IEntityLoader> mEntityLoaders = new HashMap<String, IEntityLoader>(); // =========================================================== // Constructors // =========================================================== public LevelLoader() { this(""); } public LevelLoader(final String pAssetBasePath) { this.setAssetBasePath(pAssetBasePath); } // =========================================================== // Getter & Setter // =========================================================== public IEntityLoader getDefaultEntityLoader() { return this.mDefaultEntityLoader; } public void setDefaultEntityLoader(IEntityLoader pDefaultEntityLoader) { this.mDefaultEntityLoader = pDefaultEntityLoader; } /** * @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>. */ public void setAssetBasePath(final String pAssetBasePath) { if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) { this.mAssetBasePath = pAssetBasePath; } else { throw new IllegalStateException("pAssetBasePath must end with '/' or be lenght zero."); } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected void onAfterLoadLevel() { } protected void onBeforeLoadLevel() { } // =========================================================== // Methods // =========================================================== public void registerEntityLoader(final String pEntityName, final IEntityLoader pEntityLoader) { this.mEntityLoaders.put(pEntityName, pEntityLoader); } public void registerEntityLoader(final String[] pEntityNames, final IEntityLoader pEntityLoader) { final HashMap<String, IEntityLoader> entityLoaders = this.mEntityLoaders; for(int i = pEntityNames.length - 1; i >= 0; i--) { entityLoaders.put(pEntityNames[i], pEntityLoader); } } public void loadLevelFromAsset(final Context pContext, final String pAssetPath) throws IOException { this.loadLevelFromStream(pContext.getAssets().open(this.mAssetBasePath + pAssetPath)); } public void loadLevelFromResource(final Context pContext, final int pRawResourceID) throws IOException { this.loadLevelFromStream(pContext.getResources().openRawResource(pRawResourceID)); } public void loadLevelFromStream(final InputStream pInputStream) throws IOException { try{ final SAXParserFactory spf = SAXParserFactory.newInstance(); final SAXParser sp = spf.newSAXParser(); final XMLReader xr = sp.getXMLReader(); this.onBeforeLoadLevel(); final LevelParser levelParser = new LevelParser(this.mDefaultEntityLoader, this.mEntityLoaders); xr.setContentHandler(levelParser); xr.parse(new InputSource(new BufferedInputStream(pInputStream))); this.onAfterLoadLevel(); } catch (final SAXException se) { Debug.e(se); /* Doesn't happen. */ } catch (final ParserConfigurationException pe) { Debug.e(pe); /* Doesn't happen. */ } finally { StreamUtils.close(pInputStream); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IEntityLoader { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public void onLoadEntity(final String pEntityName, final Attributes pAttributes); } }
Java
package org.anddev.andengine.level; import java.util.HashMap; import org.anddev.andengine.level.LevelLoader.IEntityLoader; import org.anddev.andengine.level.util.constants.LevelConstants; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:35:32 - 11.10.2010 */ public class LevelParser extends DefaultHandler implements LevelConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final IEntityLoader mDefaultEntityLoader; private final HashMap<String, IEntityLoader> mEntityLoaders; // =========================================================== // Constructors // =========================================================== public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap<String, IEntityLoader> pEntityLoaders) { this.mDefaultEntityLoader = pDefaultEntityLoader; this.mEntityLoaders = pEntityLoaders; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException { final IEntityLoader entityLoader = this.mEntityLoaders.get(pLocalName); if(entityLoader != null) { entityLoader.onLoadEntity(pLocalName, pAttributes); } else { if(this.mDefaultEntityLoader != null) { this.mDefaultEntityLoader.onLoadEntity(pLocalName, pAttributes); } else { throw new IllegalArgumentException("Unexpected tag: '" + pLocalName + "'."); } } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import org.anddev.andengine.entity.IEntity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 00:53:22 - 28.08.2010 */ public class EntityDetachRunnablePoolItem extends RunnablePoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected IEntity mEntity; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public void setEntity(final IEntity pEntity) { this.mEntity = pEntity; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void run() { this.mEntity.detachSelf(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:46:50 - 27.08.2010 */ public abstract class RunnablePoolItem extends PoolItem implements Runnable { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:16:25 - 31.08.2010 */ public class EntityDetachRunnablePoolUpdateHandler extends RunnablePoolUpdateHandler<EntityDetachRunnablePoolItem> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected EntityDetachRunnablePoolItem onAllocatePoolItem() { return new EntityDetachRunnablePoolItem(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:00:21 - 21.08.2010 * @param <T> */ public abstract class Pool<T extends PoolItem> extends GenericPool<T>{ // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public Pool() { super(); } public Pool(final int pInitialSize) { super(pInitialSize); } public Pool(final int pInitialSize, final int pGrowth) { super(pInitialSize, pGrowth); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected T onHandleAllocatePoolItem() { final T poolItem = super.onHandleAllocatePoolItem(); poolItem.mParent = this; return poolItem; } @Override protected void onHandleObtainItem(final T pPoolItem) { pPoolItem.mRecycled = false; pPoolItem.onObtain(); } @Override protected void onHandleRecycleItem(final T pPoolItem) { pPoolItem.onRecycle(); pPoolItem.mRecycled = true; } @Override public synchronized void recyclePoolItem(final T pPoolItem) { if(pPoolItem.mParent == null) { throw new IllegalArgumentException("PoolItem not assigned to a pool!"); } else if(!pPoolItem.isFromPool(this)) { throw new IllegalArgumentException("PoolItem from another pool!"); } else if(pPoolItem.isRecycled()) { throw new IllegalArgumentException("PoolItem already recycled!"); } super.recyclePoolItem(pPoolItem); } // =========================================================== // Methods // =========================================================== public synchronized boolean ownsPoolItem(final T pPoolItem) { return pPoolItem.mParent == this; } @SuppressWarnings("unchecked") void recycle(final PoolItem pPoolItem) { this.recyclePoolItem((T) pPoolItem); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import java.util.ArrayList; import org.anddev.andengine.engine.handler.IUpdateHandler; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:02:58 - 21.08.2010 * @param <T> */ public abstract class PoolUpdateHandler<T extends PoolItem> implements IUpdateHandler { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Pool<T> mPool; private final ArrayList<T> mScheduledPoolItems = new ArrayList<T>(); // =========================================================== // Constructors // =========================================================== public PoolUpdateHandler() { this.mPool = new Pool<T>() { @Override protected T onAllocatePoolItem() { return PoolUpdateHandler.this.onAllocatePoolItem(); } }; } public PoolUpdateHandler(final int pInitialPoolSize) { this.mPool = new Pool<T>(pInitialPoolSize) { @Override protected T onAllocatePoolItem() { return PoolUpdateHandler.this.onAllocatePoolItem(); } }; } public PoolUpdateHandler(final int pInitialPoolSize, final int pGrowth) { this.mPool = new Pool<T>(pInitialPoolSize, pGrowth) { @Override protected T onAllocatePoolItem() { return PoolUpdateHandler.this.onAllocatePoolItem(); } }; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract T onAllocatePoolItem(); protected abstract void onHandlePoolItem(final T pPoolItem); @Override public void onUpdate(final float pSecondsElapsed) { final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems; synchronized (scheduledPoolItems) { final int count = scheduledPoolItems.size(); if(count > 0) { final Pool<T> pool = this.mPool; T item; for(int i = 0; i < count; i++) { item = scheduledPoolItems.get(i); this.onHandlePoolItem(item); pool.recyclePoolItem(item); } scheduledPoolItems.clear(); } } } @Override public void reset() { final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems; synchronized (scheduledPoolItems) { final int count = scheduledPoolItems.size(); final Pool<T> pool = this.mPool; for(int i = count - 1; i >= 0; i--) { pool.recyclePoolItem(scheduledPoolItems.get(i)); } scheduledPoolItems.clear(); } } // =========================================================== // Methods // =========================================================== public T obtainPoolItem() { return this.mPool.obtainPoolItem(); } public void postPoolItem(final T pPoolItem) { synchronized (this.mScheduledPoolItems) { if(pPoolItem == null) { throw new IllegalArgumentException("PoolItem already recycled!"); } else if(!this.mPool.ownsPoolItem(pPoolItem)) { throw new IllegalArgumentException("PoolItem from another pool!"); } this.mScheduledPoolItems.add(pPoolItem); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:02:47 - 21.08.2010 */ public abstract class PoolItem { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== Pool<? extends PoolItem> mParent; boolean mRecycled = true; // =========================================================== // Constructors // =========================================================== public Pool<? extends PoolItem> getParent() { return this.mParent; } // =========================================================== // Getter & Setter // =========================================================== public boolean isRecycled() { return this.mRecycled; } public boolean isFromPool(final Pool<? extends PoolItem> pPool) { return pPool == this.mParent; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== protected void onRecycle() { } protected void onObtain() { } public void recycle() { if(this.mParent == null) { throw new IllegalStateException("Item already recycled!"); } this.mParent.recycle(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:13:26 - 02.03.2011 */ public class MultiPool<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final SparseArray<GenericPool<T>> mPools = new SparseArray<GenericPool<T>>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void registerPool(final int pID, final GenericPool<T> pPool) { this.mPools.put(pID, pPool); } public T obtainPoolItem(final int pID) { final GenericPool<T> pool = this.mPools.get(pID); if(pool == null) { return null; } else { return pool.obtainPoolItem(); } } public void recyclePoolItem(final int pID, final T pItem) { final GenericPool<T> pool = this.mPools.get(pID); if(pool != null) { pool.recyclePoolItem(pItem); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; import java.util.Collections; import java.util.Stack; import org.anddev.andengine.util.Debug; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 22:19:55 - 31.08.2010 * @param <T> */ public abstract class GenericPool<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final Stack<T> mAvailableItems = new Stack<T>(); private int mUnrecycledCount; private final int mGrowth; // =========================================================== // Constructors // =========================================================== public GenericPool() { this(0); } public GenericPool(final int pInitialSize) { this(pInitialSize, 1); } public GenericPool(final int pInitialSize, final int pGrowth) { if(pGrowth < 0) { throw new IllegalArgumentException("pGrowth must be at least 0!"); } this.mGrowth = pGrowth; if(pInitialSize > 0) { this.batchAllocatePoolItems(pInitialSize); } } // =========================================================== // Getter & Setter // =========================================================== public synchronized int getUnrecycledCount() { return this.mUnrecycledCount; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract T onAllocatePoolItem(); // =========================================================== // Methods // =========================================================== /** * @param pItem every item passes this method just before it gets recycled. */ protected void onHandleRecycleItem(final T pItem) { } protected T onHandleAllocatePoolItem() { return this.onAllocatePoolItem(); } /** * @param pItem every item that was just obtained from the pool, passes this method. */ protected void onHandleObtainItem(final T pItem) { } public synchronized void batchAllocatePoolItems(final int pCount) { final Stack<T> availableItems = this.mAvailableItems; for(int i = pCount - 1; i >= 0; i--) { availableItems.push(this.onHandleAllocatePoolItem()); } } public synchronized T obtainPoolItem() { final T item; if(this.mAvailableItems.size() > 0) { item = this.mAvailableItems.pop(); } else { if(this.mGrowth == 1) { item = this.onHandleAllocatePoolItem(); } else { this.batchAllocatePoolItems(this.mGrowth); item = this.mAvailableItems.pop(); } Debug.i(this.getClass().getName() + "<" + item.getClass().getSimpleName() +"> was exhausted, with " + this.mUnrecycledCount + " item not yet recycled. Allocated " + this.mGrowth + " more."); } this.onHandleObtainItem(item); this.mUnrecycledCount++; return item; } public synchronized void recyclePoolItem(final T pItem) { if(pItem == null) { throw new IllegalArgumentException("Cannot recycle null item!"); } this.onHandleRecycleItem(pItem); this.mAvailableItems.push(pItem); this.mUnrecycledCount--; if(this.mUnrecycledCount < 0) { Debug.e("More items recycled than obtained!"); } } public synchronized void shufflePoolItems() { Collections.shuffle(this.mAvailableItems); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.pool; /** * @author Valentin Milea * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * * @since 23:03:58 - 21.08.2010 * @param <T> */ public abstract class RunnablePoolUpdateHandler<T extends RunnablePoolItem> extends PoolUpdateHandler<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public RunnablePoolUpdateHandler() { } public RunnablePoolUpdateHandler(final int pInitialPoolSize) { super(pInitialPoolSize); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected abstract T onAllocatePoolItem(); @Override protected void onHandlePoolItem(final T pRunnablePoolItem) { pRunnablePoolItem.run(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.os.Environment; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 13:53:33 - 20.06.2010 */ public class FileUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); } public static void copyToInternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException { FileUtils.copyToInternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename); } public static void copyToExternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException { FileUtils.copyToExternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename); } public static void copyToInternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException { FileUtils.copyToInternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename); } private static void copyToInternalStorage(final Context pContext, final InputStream pInputStream, final String pFilename) throws FileNotFoundException { StreamUtils.copyAndClose(pInputStream, new FileOutputStream(new File(pContext.getFilesDir(), pFilename))); } public static void copyToExternalStorage(final Context pContext, final InputStream pInputStream, final String pFilePath) throws FileNotFoundException { if (FileUtils.isExternalStorageWriteable()) { final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); StreamUtils.copyAndClose(pInputStream, new FileOutputStream(absoluteFilePath)); } else { throw new IllegalStateException("External Storage is not writeable."); } } public static boolean isFileExistingOnExternalStorage(final Context pContext, final String pFilePath) { if (FileUtils.isExternalStorageReadable()) { final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); final File file = new File(absoluteFilePath); return file.exists()&& file.isFile(); } else { throw new IllegalStateException("External Storage is not readable."); } } public static boolean isDirectoryExistingOnExternalStorage(final Context pContext, final String pDirectory) { if (FileUtils.isExternalStorageReadable()) { final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory); final File file = new File(absoluteFilePath); return file.exists() && file.isDirectory(); } else { throw new IllegalStateException("External Storage is not readable."); } } public static boolean ensureDirectoriesExistOnExternalStorage(final Context pContext, final String pDirectory) { if(FileUtils.isDirectoryExistingOnExternalStorage(pContext, pDirectory)) { return true; } if (FileUtils.isExternalStorageWriteable()) { final String absoluteDirectoryPath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory); return new File(absoluteDirectoryPath).mkdirs(); } else { throw new IllegalStateException("External Storage is not writeable."); } } public static InputStream openOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException { final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); return new FileInputStream(absoluteFilePath); } public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException { final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); return new File(absoluteFilePath).list(); } public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath, final FilenameFilter pFilenameFilter) throws FileNotFoundException { final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath); return new File(absoluteFilePath).list(pFilenameFilter); } public static String getAbsolutePathOnInternalStorage(final Context pContext, final String pFilePath) { return pContext.getFilesDir().getAbsolutePath() + pFilePath; } public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) { return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath; } public static boolean isExternalStorageWriteable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } public static boolean isExternalStorageReadable() { final String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY); } public static void copyFile(final File pIn, final File pOut) throws IOException { final FileInputStream fis = new FileInputStream(pIn); final FileOutputStream fos = new FileOutputStream(pOut); try { StreamUtils.copy(fis, fos); } finally { StreamUtils.close(fis); StreamUtils.close(fos); } } /** * Deletes all files and sub-directories under <code>dir</code>. Returns * true if all deletions were successful. If a deletion fails, the method * stops attempting to delete and returns false. * * @param pFileOrDirectory * @return */ public static boolean deleteDirectory(final File pFileOrDirectory) { if(pFileOrDirectory.isDirectory()) { final String[] children = pFileOrDirectory.list(); final int childrenCount = children.length; for(int i = 0; i < childrenCount; i++) { final boolean success = FileUtils.deleteDirectory(new File(pFileOrDirectory, children[i])); if(!success) { return false; } } } // The directory is now empty so delete it return pFileOrDirectory.delete(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import org.anddev.andengine.util.constants.Constants; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:55:12 - 02.08.2010 */ public class SimplePreferences implements Constants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static SharedPreferences INSTANCE; private static Editor EDITORINSTANCE; // =========================================================== // Constructors // =========================================================== public static SharedPreferences getInstance(final Context pContext) { if(SimplePreferences.INSTANCE == null) { SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); } return SimplePreferences.INSTANCE; } public static Editor getEditorInstance(final Context pContext) { if(SimplePreferences.EDITORINSTANCE == null) { SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); } return SimplePreferences.EDITORINSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static int incrementAccessCount(final Context pContext, final String pKey) { return SimplePreferences.incrementAccessCount(pContext, pKey, 1); } public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) { final SharedPreferences prefs = SimplePreferences.getInstance(pContext); final int accessCount = prefs.getInt(pKey, 0); final int newAccessCount = accessCount + pIncrement; prefs.edit().putInt(pKey, newAccessCount).commit(); return newAccessCount; } public static int getAccessCount(final Context pCtx, final String pKey) { return SimplePreferences.getInstance(pCtx).getInt(pKey, 0); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import java.util.ArrayList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:20:08 - 27.12.2010 */ public class SmartList<T> extends ArrayList<T> { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = -8335986399182700102L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public SmartList() { } public SmartList(final int pCapacity) { super(pCapacity); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * @param pItem the item to remove. * @param pParameterCallable to be called with the removed item, if it was removed. */ public boolean remove(final T pItem, final ParameterCallable<T> pParameterCallable) { final boolean removed = this.remove(pItem); if(removed) { pParameterCallable.call(pItem); } return removed; } public T remove(final IMatcher<T> pMatcher) { for(int i = 0; i < this.size(); i++) { if(pMatcher.matches(this.get(i))) { return this.remove(i); } } return null; } public T remove(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i--) { if(pMatcher.matches(this.get(i))) { final T removed = this.remove(i); pParameterCallable.call(removed); return removed; } } return null; } public boolean removeAll(final IMatcher<T> pMatcher) { boolean result = false; for(int i = this.size() - 1; i >= 0; i--) { if(pMatcher.matches(this.get(i))) { this.remove(i); result = true; } } return result; } /** * @param pMatcher to find the items. * @param pParameterCallable to be called with each matched item after it was removed. */ public boolean removeAll(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) { boolean result = false; for(int i = this.size() - 1; i >= 0; i--) { if(pMatcher.matches(this.get(i))) { final T removed = this.remove(i); pParameterCallable.call(removed); result = true; } } return result; } public void clear(final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i--) { final T removed = this.remove(i); pParameterCallable.call(removed); } } public T find(final IMatcher<T> pMatcher) { for(int i = this.size() - 1; i >= 0; i--) { final T item = this.get(i); if(pMatcher.matches(item)) { return item; } } return null; } public void call(final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i--) { final T item = this.get(i); pParameterCallable.call(item); } } public void call(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) { for(int i = this.size() - 1; i >= 0; i--) { final T item = this.get(i); if(pMatcher.matches(item)) { pParameterCallable.call(item); } } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:55:35 - 08.09.2009 */ public class ViewUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static View inflate(final Context pContext, final int pLayoutID){ return LayoutInflater.from(pContext).inflate(pLayoutID, null); } public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){ return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:15:23 - 24.07.2010 */ public enum VerticalAlign { // =========================================================== // Elements // =========================================================== TOP, CENTER, BOTTOM; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.sort; import java.util.Comparator; import java.util.List; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:14:31 - 06.08.2010 * @param <T> */ public class InsertionSorter<T> extends Sorter<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator) { for(int i = pStart + 1; i < pEnd; i++) { final T current = pArray[i]; T prev = pArray[i - 1]; if(pComparator.compare(current, prev) < 0) { int j = i; do { pArray[j--] = prev; } while(j > pStart && pComparator.compare(current, prev = pArray[j - 1]) < 0); pArray[j] = current; } } return; } @Override public void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator) { for(int i = pStart + 1; i < pEnd; i++) { final T current = pList.get(i); T prev = pList.get(i - 1); if(pComparator.compare(current, prev) < 0) { int j = i; do { pList.set(j--, prev); } while(j > pStart && pComparator.compare(current, prev = pList.get(j - 1)) < 0); pList.set(j, current); } } return; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.sort; import java.util.Comparator; import java.util.List; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:14:39 - 06.08.2010 * @param <T> */ public abstract class Sorter<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public abstract void sort(final T[] pArray, final int pStart, final int pEnd, final Comparator<T> pComparator); public abstract void sort(final List<T> pList, final int pStart, final int pEnd, final Comparator<T> pComparator); // =========================================================== // Methods // =========================================================== public final void sort(final T[] pArray, final Comparator<T> pComparator){ this.sort(pArray, 0, pArray.length, pComparator); } public final void sort(final List<T> pList, final Comparator<T> pComparator){ this.sort(pList, 0, pList.size(), pComparator); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:47:33 - 11.05.2010 */ public enum HorizontalAlign { // =========================================================== // Elements // =========================================================== LEFT, CENTER, RIGHT; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import java.util.concurrent.Callable; import org.anddev.andengine.ui.activity.BaseActivity.CancelledException; import org.anddev.andengine.util.progress.IProgressListener; import org.anddev.andengine.util.progress.ProgressCallable; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.view.Window; import android.view.WindowManager; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:11:54 - 07.03.2011 */ public class ActivityUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static void requestFullscreen(final Activity pActivity) { final Window window = pActivity.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); window.requestFeature(Window.FEATURE_NO_TITLE); } /** * @param pActivity * @param pScreenBrightness [0..1] */ public static void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) { final Window window = pActivity.getWindow(); final WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); windowLayoutParams.screenBrightness = pScreenBrightness; window.setAttributes(windowLayoutParams); } public static void keepScreenOn(final Activity pActivity) { pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) { ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false); } public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback) { ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false); } public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) { ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, pCancelable); } public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) { ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable); } public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback, false); } public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false); } public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) { ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), pCallable, pCallback, pExceptionCallback, pCancelable); } public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) { new AsyncTask<Void, Void, T>() { private ProgressDialog mPD; private Exception mException = null; @Override public void onPreExecute() { this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable); if(pCancelable) { this.mPD.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(final DialogInterface pDialogInterface) { pExceptionCallback.onCallback(new CancelledException()); pDialogInterface.dismiss(); } }); } super.onPreExecute(); } @Override public T doInBackground(final Void... params) { try { return pCallable.call(); } catch (final Exception e) { this.mException = e; } return null; } @Override public void onPostExecute(final T result) { try { this.mPD.dismiss(); } catch (final Exception e) { Debug.e("Error", e); } if(this.isCancelled()) { this.mException = new CancelledException(); } if(this.mException == null) { pCallback.onCallback(result); } else { if(pExceptionCallback == null) { Debug.e("Error", this.mException); } else { pExceptionCallback.onCallback(this.mException); } } super.onPostExecute(result); } }.execute((Void[]) null); } public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) { ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null); } public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { new AsyncTask<Void, Integer, T>() { private ProgressDialog mPD; private Exception mException = null; @Override public void onPreExecute() { this.mPD = new ProgressDialog(pContext); this.mPD.setTitle(pTitleResID); this.mPD.setIcon(android.R.drawable.ic_menu_save); this.mPD.setIndeterminate(false); this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); this.mPD.show(); super.onPreExecute(); } @Override public T doInBackground(final Void... params) { try { return pCallable.call(new IProgressListener() { @Override public void onProgressChanged(final int pProgress) { onProgressUpdate(pProgress); } }); } catch (final Exception e) { this.mException = e; } return null; } @Override public void onProgressUpdate(final Integer... values) { this.mPD.setProgress(values[0]); } @Override public void onPostExecute(final T result) { try { this.mPD.dismiss(); } catch (final Exception e) { Debug.e("Error", e); /* Nothing. */ } if(this.isCancelled()) { this.mException = new CancelledException(); } if(this.mException == null) { pCallback.onCallback(result); } else { if(pExceptionCallback == null) { Debug.e("Error", this.mException); } else { pExceptionCallback.onCallback(this.mException); } } super.onPostExecute(result); } }.execute((Void[]) null); } public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID)); pAsyncCallable.call(new Callback<T>() { @Override public void onCallback(final T result) { try { pd.dismiss(); } catch (final Exception e) { Debug.e("Error", e); /* Nothing. */ } pCallback.onCallback(result); } }, pExceptionCallback); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ public interface ITiledMap<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int getTileColumns(); public int getTileRows(); public void onTileVisitedByPathFinder(final int pTileColumn, int pTileRow); public boolean isTileBlocked(final T pEntity, final int pTileColumn, final int pTileRow); public float getStepCost(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); }
Java
package org.anddev.andengine.util.path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:19:11 - 17.08.2010 */ public enum Direction { // =========================================================== // Elements // =========================================================== UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mDeltaX; private final int mDeltaY; // =========================================================== // Constructors // =========================================================== private Direction(final int pDeltaX, final int pDeltaY) { this.mDeltaX = pDeltaX; this.mDeltaY = pDeltaY; } public static Direction fromDelta(final int pDeltaX, final int pDeltaY) { if(pDeltaX == 0) { if(pDeltaY == 1) { return DOWN; } else if(pDeltaY == -1) { return UP; } } else if (pDeltaY == 0) { if(pDeltaX == 1) { return RIGHT; } else if(pDeltaX == -1) { return LEFT; } } throw new IllegalArgumentException(); } // =========================================================== // Getter & Setter // =========================================================== public int getDeltaX() { return this.mDeltaX; } public int getDeltaY() { return this.mDeltaY; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:57:13 - 16.08.2010 */ public interface IPathFinder<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ public class ManhattanHeuristic<T> implements IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { return Math.abs(pTileFromX - pTileToX) + Math.abs(pTileToX - pTileToY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ public class EuclideanHeuristic<T> implements IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getExpectedRestCost(final ITiledMap<T> pTileMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { final float dX = pTileToX - pTileFromX; final float dY = pTileToY - pTileFromY; return FloatMath.sqrt(dX * dX + dY * dY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:58:01 - 16.08.2010 */ public class NullHeuristic<T> implements IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pTileFromX, final int pTileFromY, final int pTileToX, final int pTileToY) { return 0; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.path.astar; import org.anddev.andengine.util.path.ITiledMap; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:59:20 - 16.08.2010 */ public interface IAStarHeuristic<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public float getExpectedRestCost(final ITiledMap<T> pTiledMap, final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow); }
Java
package org.anddev.andengine.util.path.astar; import java.util.ArrayList; import java.util.Collections; import org.anddev.andengine.util.path.IPathFinder; import org.anddev.andengine.util.path.ITiledMap; import org.anddev.andengine.util.path.Path; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:16:17 - 16.08.2010 */ public class AStarPathFinder<T> implements IPathFinder<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ArrayList<Node> mVisitedNodes = new ArrayList<Node>(); private final ArrayList<Node> mOpenNodes = new ArrayList<Node>(); private final ITiledMap<T> mTiledMap; private final int mMaxSearchDepth; private final Node[][] mNodes; private final boolean mAllowDiagonalMovement; private final IAStarHeuristic<T> mAStarHeuristic; // =========================================================== // Constructors // =========================================================== public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement) { this(pTiledMap, pMaxSearchDepth, pAllowDiagonalMovement, new EuclideanHeuristic<T>()); } public AStarPathFinder(final ITiledMap<T> pTiledMap, final int pMaxSearchDepth, final boolean pAllowDiagonalMovement, final IAStarHeuristic<T> pAStarHeuristic) { this.mAStarHeuristic = pAStarHeuristic; this.mTiledMap = pTiledMap; this.mMaxSearchDepth = pMaxSearchDepth; this.mAllowDiagonalMovement = pAllowDiagonalMovement; this.mNodes = new Node[pTiledMap.getTileRows()][pTiledMap.getTileColumns()]; final Node[][] nodes = this.mNodes; for(int x = pTiledMap.getTileColumns() - 1; x >= 0; x--) { for(int y = pTiledMap.getTileRows() - 1; y >= 0; y--) { nodes[y][x] = new Node(x, y); } } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Path findPath(final T pEntity, final int pMaxCost, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { final ITiledMap<T> tiledMap = this.mTiledMap; if(tiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow)) { return null; } /* Drag some fields to local variables. */ final ArrayList<Node> openNodes = this.mOpenNodes; final ArrayList<Node> visitedNodes = this.mVisitedNodes; final Node[][] nodes = this.mNodes; final Node fromNode = nodes[pFromTileRow][pFromTileColumn]; final Node toNode = nodes[pToTileRow][pToTileColumn]; final IAStarHeuristic<T> aStarHeuristic = this.mAStarHeuristic; final boolean allowDiagonalMovement = this.mAllowDiagonalMovement; final int maxSearchDepth = this.mMaxSearchDepth; /* Initialize algorithm. */ fromNode.mCost = 0; fromNode.mDepth = 0; toNode.mParent = null; visitedNodes.clear(); openNodes.clear(); openNodes.add(fromNode); int currentDepth = 0; while(currentDepth < maxSearchDepth && !openNodes.isEmpty()) { /* The first Node in the open list is the one with the lowest cost. */ final Node current = openNodes.remove(0); if(current == toNode) { break; } visitedNodes.add(current); /* Loop over all neighbors of this tile. */ for(int dX = -1; dX <= 1; dX++) { for(int dY = -1; dY <= 1; dY++) { if((dX == 0) && (dY == 0)) { continue; } if(!allowDiagonalMovement) { if((dX != 0) && (dY != 0)) { continue; } } final int neighborTileColumn = dX + current.mTileColumn; final int neighborTileRow = dY + current.mTileRow; if(!this.isTileBlocked(pEntity, pFromTileColumn, pFromTileRow, neighborTileColumn, neighborTileRow)) { final float neighborCost = current.mCost + tiledMap.getStepCost(pEntity, current.mTileColumn, current.mTileRow, neighborTileColumn, neighborTileRow); final Node neighbor = nodes[neighborTileRow][neighborTileColumn]; tiledMap.onTileVisitedByPathFinder(neighborTileColumn, neighborTileRow); /* Re-evaluate if there is a better path. */ if(neighborCost < neighbor.mCost) { // TODO Is this ever possible with AStar ?? if(openNodes.contains(neighbor)) { openNodes.remove(neighbor); } if(visitedNodes.contains(neighbor)) { visitedNodes.remove(neighbor); } } if(!openNodes.contains(neighbor) && !(visitedNodes.contains(neighbor))) { neighbor.mCost = neighborCost; if(neighbor.mCost <= pMaxCost) { neighbor.mExpectedRestCost = aStarHeuristic.getExpectedRestCost(tiledMap, pEntity, neighborTileColumn, neighborTileRow, pToTileColumn, pToTileRow); currentDepth = Math.max(currentDepth, neighbor.setParent(current)); openNodes.add(neighbor); /* Ensure always the node with the lowest cost+heuristic * will be used next, simply by sorting. */ Collections.sort(openNodes); } } } } } } /* Check if a path was found. */ if(toNode.mParent == null) { return null; } /* Traceback path. */ final Path path = new Path(); Node tmp = nodes[pToTileRow][pToTileColumn]; while(tmp != fromNode) { path.prepend(tmp.mTileColumn, tmp.mTileRow); tmp = tmp.mParent; } path.prepend(pFromTileColumn, pFromTileRow); return path; } // =========================================================== // Methods // =========================================================== protected boolean isTileBlocked(final T pEntity, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow) { if((pToTileColumn < 0) || (pToTileRow < 0) || (pToTileColumn >= this.mTiledMap.getTileColumns()) || (pToTileRow >= this.mTiledMap.getTileRows())) { return true; } else if((pFromTileColumn == pToTileColumn) && (pFromTileRow == pToTileRow)) { return true; } return this.mTiledMap.isTileBlocked(pEntity, pToTileColumn, pToTileRow); } // =========================================================== // Inner and Anonymous Classes // =========================================================== private static class Node implements Comparable<Node> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== Node mParent; int mDepth; final int mTileColumn; final int mTileRow; float mCost; float mExpectedRestCost; // =========================================================== // Constructors // =========================================================== public Node(final int pTileColumn, final int pTileRow) { this.mTileColumn = pTileColumn; this.mTileRow = pTileRow; } // =========================================================== // Getter & Setter // =========================================================== public int setParent(final Node parent) { this.mDepth = parent.mDepth + 1; this.mParent = parent; return this.mDepth; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int compareTo(final Node pOther) { final float totalCost = this.mExpectedRestCost + this.mCost; final float totalCostOther = pOther.mExpectedRestCost + pOther.mCost; if (totalCost < totalCostOther) { return -1; } else if (totalCost > totalCostOther) { return 1; } else { return 0; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.util.path; import java.util.ArrayList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:00:24 - 16.08.2010 */ public class Path { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final ArrayList<Step> mSteps = new ArrayList<Step>(); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== public int getLength() { return this.mSteps.size(); } public Step getStep(final int pIndex) { return this.mSteps.get(pIndex); } public Direction getDirectionToPreviousStep(final int pIndex) { if(pIndex == 0) { return null; } else { final int dX = this.getTileColumn(pIndex - 1) - this.getTileColumn(pIndex); final int dY = this.getTileRow(pIndex - 1) - this.getTileRow(pIndex); return Direction.fromDelta(dX, dY); } } public Direction getDirectionToNextStep(final int pIndex) { if(pIndex == this.getLength() - 1) { return null; } else { final int dX = this.getTileColumn(pIndex + 1) - this.getTileColumn(pIndex); final int dY = this.getTileRow(pIndex + 1) - this.getTileRow(pIndex); return Direction.fromDelta(dX, dY); } } public int getTileColumn(final int pIndex) { return this.getStep(pIndex).getTileColumn(); } public int getTileRow(final int pIndex) { return this.getStep(pIndex).getTileRow(); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void append(final int pTileColumn, final int pTileRow) { this.append(new Step(pTileColumn, pTileRow)); } public void append(final Step pStep) { this.mSteps.add(pStep); } public void prepend(final int pTileColumn, final int pTileRow) { this.prepend(new Step(pTileColumn, pTileRow)); } public void prepend(final Step pStep) { this.mSteps.add(0, pStep); } public boolean contains(final int pTileColumn, final int pTileRow) { final ArrayList<Step> steps = this.mSteps; for(int i = steps.size() - 1; i >= 0; i--) { final Step step = steps.get(i); if(step.getTileColumn() == pTileColumn && step.getTileRow() == pTileRow) { return true; } } return false; } public int getFromTileRow() { return this.getTileRow(0); } public int getFromTileColumn() { return this.getTileColumn(0); } public int getToTileRow() { return this.getTileRow(this.mSteps.size() - 1); } public int getToTileColumn() { return this.getTileColumn(this.mSteps.size() - 1); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public class Step { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final int mTileColumn; private final int mTileRow; // =========================================================== // Constructors // =========================================================== public Step(final int pTileColumn, final int pTileRow) { this.mTileColumn = pTileColumn; this.mTileRow = pTileRow; } // =========================================================== // Getter & Setter // =========================================================== public int getTileColumn() { return this.mTileColumn; } public int getTileRow() { return this.mTileRow; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public int hashCode() { return this.mTileColumn << 16 + this.mTileRow; } @Override public boolean equals(final Object pOther) { if(this == pOther) { return true; } if(pOther == null) { return false; } if(this.getClass() != pOther.getClass()) { return false; } final Step other = (Step) pOther; if(this.mTileColumn != other.mTileColumn) { return false; } if(this.mTileRow != other.mTileRow) { return false; } return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.util; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.util.Scanner; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:48:56 - 03.09.2009 */ public class StreamUtils { // =========================================================== // Constants // =========================================================== public static final int IO_BUFFER_SIZE = 8 * 1024; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static final String readFully(final InputStream pInputStream) throws IOException { final StringBuilder sb = new StringBuilder(); final Scanner sc = new Scanner(pInputStream); while(sc.hasNextLine()) { sb.append(sc.nextLine()); } return sb.toString(); } public static byte[] streamToBytes(final InputStream pInputStream) throws IOException { return StreamUtils.streamToBytes(pInputStream, -1); } public static byte[] streamToBytes(final InputStream pInputStream, final int pReadLimit) throws IOException { final ByteArrayOutputStream os = new ByteArrayOutputStream((pReadLimit == -1) ? IO_BUFFER_SIZE : pReadLimit); StreamUtils.copy(pInputStream, os, pReadLimit); return os.toByteArray(); } public static void copy(final InputStream pInputStream, final OutputStream pOutputStream) throws IOException { StreamUtils.copy(pInputStream, pOutputStream, -1); } public static boolean copyAndClose(final InputStream pInputStream, final OutputStream pOutputStream) { try { StreamUtils.copy(pInputStream, pOutputStream, -1); return true; } catch (final IOException e) { return false; } finally { StreamUtils.close(pInputStream); StreamUtils.close(pOutputStream); } } /** * Copy the content of the input stream into the output stream, using a temporary * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. * * @param pInputStream The input stream to copy from. * @param pOutputStream The output stream to copy to. * @param pByteLimit not more than so much bytes to read, or unlimited if smaller than 0. * * @throws IOException If any error occurs during the copy. */ public static void copy(final InputStream pInputStream, final OutputStream pOutputStream, final long pByteLimit) throws IOException { if(pByteLimit < 0) { final byte[] b = new byte[IO_BUFFER_SIZE]; int read; while((read = pInputStream.read(b)) != -1) { pOutputStream.write(b, 0, read); } } else { final byte[] b = new byte[IO_BUFFER_SIZE]; final int bufferReadLimit = Math.min((int)pByteLimit, IO_BUFFER_SIZE); long pBytesLeftToRead = pByteLimit; int read; while((read = pInputStream.read(b, 0, bufferReadLimit)) != -1) { if(pBytesLeftToRead > read) { pOutputStream.write(b, 0, read); pBytesLeftToRead -= read; } else { pOutputStream.write(b, 0, (int) pBytesLeftToRead); break; } } } pOutputStream.flush(); } /** * Closes the specified stream. * * @param pCloseable The stream to close. */ public static void close(final Closeable pCloseable) { if(pCloseable != null) { try { pCloseable.close(); } catch (final IOException e) { e.printStackTrace(); } } } /** * Flushes and closes the specified stream. * * @param pOutputStream The stream to close. */ public static void flushCloseStream(final OutputStream pOutputStream) { if(pOutputStream != null) { try { pOutputStream.flush(); } catch (final IOException e) { e.printStackTrace(); } finally { StreamUtils.close(pOutputStream); } } } /** * Flushes and closes the specified stream. * * @param pWriter The Writer to close. */ public static void flushCloseWriter(final Writer pWriter) { if(pWriter != null) { try { pWriter.flush(); } catch (final IOException e) { e.printStackTrace(); } finally { StreamUtils.close(pWriter); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.util.FloatMath; /** * <p>This class is basically a java-space replacement for the native {@link android.graphics.Matrix} class.</p> * * <p>Math taken from <a href="http://www.senocular.com/flash/tutorials/transformmatrix/">senocular.com</a>.</p> * * This class represents an affine transformation with the following matrix: * <pre> [ a , b , 0 ] * [ c , d , 0 ] * [ tx, ty, 1 ]</pre> * where: * <ul> * <li><b>a</b> is the <b>x scale</b></li> * <li><b>b</b> is the <b>y skew</b></li> * <li><b>c</b> is the <b>x skew</b></li> * <li><b>d</b> is the <b>y scale</b></li> * <li><b>tx</b> is the <b>x translation</b></li> * <li><b>ty</b> is the <b>y translation</b></li> * </ul> * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 15:47:18 - 23.12.2010 */ public class Transformation { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float a = 1.0f; /* x scale */ private float b = 0.0f; /* y skew */ private float c = 0.0f; /* x skew */ private float d = 1.0f; /* y scale */ private float tx = 0.0f; /* x translation */ private float ty = 0.0f; /* y translation */ // =========================================================== // Constructors // =========================================================== public Transformation() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public String toString() { return "Transformation{[" + this.a + ", " + this.c + ", " + this.tx + "][" + this.b + ", " + this.d + ", " + this.ty + "][0.0, 0.0, 1.0]}"; } // =========================================================== // Methods // =========================================================== public void reset() { this.setToIdentity(); } public void setToIdentity() { this.a = 1.0f; this.d = 1.0f; this.b = 0.0f; this.c = 0.0f; this.tx = 0.0f; this.ty = 0.0f; } public void setTo(final Transformation pTransformation) { this.a = pTransformation.a; this.d = pTransformation.d; this.b = pTransformation.b; this.c = pTransformation.c; this.tx = pTransformation.tx; this.ty = pTransformation.ty; } public void preTranslate(final float pX, final float pY) { this.preConcat(1.0f, 0.0f, 0.0f, 1.0f, pX, pY); } public void postTranslate(final float pX, final float pY) { this.postConcat(1.0f, 0.0f, 0.0f, 1.0f, pX, pY); } public Transformation setToTranslate(final float pX, final float pY) { this.a = 1.0f; this.b = 0.0f; this.c = 0.0f; this.d = 1.0f; this.tx = pX; this.ty = pY; return this; } public void preScale(final float pScaleX, final float pScaleY) { this.preConcat(pScaleX, 0.0f, 0.0f, pScaleY, 0.0f, 0.0f); } public void postScale(final float pScaleX, final float pScaleY) { this.postConcat(pScaleX, 0.0f, 0.0f, pScaleY, 0.0f, 0.0f); } public Transformation setToScale(final float pScaleX, final float pScaleY) { this.a = pScaleX; this.b = 0.0f; this.c = 0.0f; this.d = pScaleY; this.tx = 0.0f; this.ty = 0.0f; return this; } public void preRotate(final float pAngle) { final float angleRad = MathUtils.degToRad(pAngle); final float sin = FloatMath.sin(angleRad); final float cos = FloatMath.cos(angleRad); this.preConcat(cos, sin, -sin, cos, 0.0f, 0.0f); } public void postRotate(final float pAngle) { final float angleRad = MathUtils.degToRad(pAngle); final float sin = FloatMath.sin(angleRad); final float cos = FloatMath.cos(angleRad); this.postConcat(cos, sin, -sin, cos, 0.0f, 0.0f); } public Transformation setToRotate(final float pAngle) { final float angleRad = MathUtils.degToRad(pAngle); final float sin = FloatMath.sin(angleRad); final float cos = FloatMath.cos(angleRad); this.a = cos; this.b = sin; this.c = -sin; this.d = cos; this.tx = 0.0f; this.ty = 0.0f; return this; } public void postConcat(final Transformation pTransformation) { this.postConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); } private void postConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { final float a = this.a; final float b = this.b; final float c = this.c; final float d = this.d; final float tx = this.tx; final float ty = this.ty; this.a = a * pA + b * pC; this.b = a * pB + b * pD; this.c = c * pA + d * pC; this.d = c * pB + d * pD; this.tx = tx * pA + ty * pC + pTX; this.ty = tx * pB + ty * pD + pTY; } public void preConcat(final Transformation pTransformation) { this.preConcat(pTransformation.a, pTransformation.b, pTransformation.c, pTransformation.d, pTransformation.tx, pTransformation.ty); } private void preConcat(final float pA, final float pB, final float pC, final float pD, final float pTX, final float pTY) { final float a = this.a; final float b = this.b; final float c = this.c; final float d = this.d; final float tx = this.tx; final float ty = this.ty; this.a = pA * a + pB * c; this.b = pA * b + pB * d; this.c = pC * a + pD * c; this.d = pC * b + pD * d; this.tx = pTX * a + pTY * c + tx; this.ty = pTX * b + pTY * d + ty; } public void transform(final float[] pVertices) { int count = pVertices.length / 2; int i = 0; int j = 0; while(--count >= 0) { final float x = pVertices[i++]; final float y = pVertices[i++]; pVertices[j++] = x * this.a + y * this.c + this.tx; pVertices[j++] = x * this.b + y * this.d + this.ty; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:13:45 - 04.08.2010 */ public class ColorUtils { // =========================================================== // Constants // =========================================================== private static final float[] HSV_TO_COLOR = new float[3]; private static final int HSV_TO_COLOR_HUE_INDEX = 0; private static final int HSV_TO_COLOR_SATURATION_INDEX = 1; private static final int HSV_TO_COLOR_VALUE_INDEX = 2; private static final int COLOR_FLOAT_TO_INT_FACTOR = 255; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== /** * @param pHue [0 .. 360) * @param pSaturation [0...1] * @param pValue [0...1] */ public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) { HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue; HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation; HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue; return Color.HSVToColor(HSV_TO_COLOR); } public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) { return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR)); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.levelstats; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.SimplePreferences; import org.anddev.andengine.util.StreamUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.content.SharedPreferences; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 21:13:55 - 18.10.2010 */ public class LevelStatsDBConnector { // =========================================================== // Constants // =========================================================== private static final String PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID = "preferences.levelstatsdbconnector.playerid"; // =========================================================== // Fields // =========================================================== private final String mSecret; private final String mSubmitURL; private final int mPlayerID; // =========================================================== // Constructors // =========================================================== public LevelStatsDBConnector(final Context pContext, final String pSecret, final String pSubmitURL) { this.mSecret = pSecret; this.mSubmitURL = pSubmitURL; final SharedPreferences simplePreferences = SimplePreferences.getInstance(pContext); final int playerID = simplePreferences.getInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, -1); if(playerID != -1) { this.mPlayerID = playerID; } else { this.mPlayerID = MathUtils.random(1000000000, Integer.MAX_VALUE); SimplePreferences.getEditorInstance(pContext).putInt(PREFERENCES_LEVELSTATSDBCONNECTOR_PLAYERID_ID, this.mPlayerID).commit(); } } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed) { this.submitAsync(pLevelID, pSolved, pSecondsElapsed, null); } public void submitAsync(final int pLevelID, final boolean pSolved, final int pSecondsElapsed, final Callback<Boolean> pCallback) { new Thread(new Runnable() { @Override public void run() { try{ /* Create a new HttpClient and Post Header. */ final HttpClient httpClient = new DefaultHttpClient(); final HttpPost httpPost = new HttpPost(LevelStatsDBConnector.this.mSubmitURL); /* Append POST data. */ final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5); nameValuePairs.add(new BasicNameValuePair("level_id", String.valueOf(pLevelID))); nameValuePairs.add(new BasicNameValuePair("solved", (pSolved) ? "1" : "0")); nameValuePairs.add(new BasicNameValuePair("secondsplayed", String.valueOf(pSecondsElapsed))); nameValuePairs.add(new BasicNameValuePair("player_id", String.valueOf(LevelStatsDBConnector.this.mPlayerID))); nameValuePairs.add(new BasicNameValuePair("secret", String.valueOf(LevelStatsDBConnector.this.mSecret))); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); /* Execute HTTP Post Request. */ final HttpResponse httpResponse = httpClient.execute(httpPost); final int statusCode = httpResponse.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK) { final String response = StreamUtils.readFully(httpResponse.getEntity().getContent()); if(response.equals("<success/>")) { if(pCallback != null) { pCallback.onCallback(true); } } else { if(pCallback != null) { pCallback.onCallback(false); } } } else { if(pCallback != null) { pCallback.onCallback(false); } } }catch(final IOException e) { Debug.e(e); if(pCallback != null) { pCallback.onCallback(false); } } } }).start(); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import android.util.SparseArray; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:51:29 - 20.08.2010 * @param <T> */ public class Library<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final SparseArray<T> mItems; // =========================================================== // Constructors // =========================================================== public Library() { this.mItems = new SparseArray<T>(); } public Library(final int pInitialCapacity) { this.mItems = new SparseArray<T>(pInitialCapacity); } // =========================================================== // Getter & Setter // =========================================================== public void put(final int pID, final T pItem) { final T existingItem = this.mItems.get(pID); if(existingItem == null) { this.mItems.put(pID, pItem); } else { throw new IllegalArgumentException("ID: '" + pID + "' is already associated with item: '" + existingItem.toString() + "'."); } } public void remove(final int pID) { this.mItems.remove(pID); } public T get(final int pID) { return this.mItems.get(pID); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.anddev.andengine.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * An InputStream that does Base64 decoding on the data read through * it. */ public class Base64InputStream extends FilterInputStream { private final Base64.Coder coder; private static byte[] EMPTY = new byte[0]; private static final int BUFFER_SIZE = 2048; private boolean eof; private byte[] inputBuffer; private int outputStart; private int outputEnd; /** * An InputStream that performs Base64 decoding on the data read * from the wrapped stream. * * @param in the InputStream to read the source data from * @param flags bit flags for controlling the decoder; see the * constants in {@link Base64} */ public Base64InputStream(final InputStream in, final int flags) { this(in, flags, false); } /** * Performs Base64 encoding or decoding on the data read from the * wrapped InputStream. * * @param in the InputStream to read the source data from * @param flags bit flags for controlling the decoder; see the * constants in {@link Base64} * @param encode true to encode, false to decode * * @hide */ public Base64InputStream(final InputStream in, final int flags, final boolean encode) { super(in); this.eof = false; this.inputBuffer = new byte[BUFFER_SIZE]; if (encode) { this.coder = new Base64.Encoder(flags, null); } else { this.coder = new Base64.Decoder(flags, null); } this.coder.output = new byte[this.coder.maxOutputSize(BUFFER_SIZE)]; this.outputStart = 0; this.outputEnd = 0; } @Override public boolean markSupported() { return false; } @Override public void mark(final int readlimit) { throw new UnsupportedOperationException(); } @Override public void reset() { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { this.in.close(); this.inputBuffer = null; } @Override public int available() { return this.outputEnd - this.outputStart; } @Override public long skip(final long n) throws IOException { if (this.outputStart >= this.outputEnd) { this.refill(); } if (this.outputStart >= this.outputEnd) { return 0; } final long bytes = Math.min(n, this.outputEnd-this.outputStart); this.outputStart += bytes; return bytes; } @Override public int read() throws IOException { if (this.outputStart >= this.outputEnd) { this.refill(); } if (this.outputStart >= this.outputEnd) { return -1; } else { return this.coder.output[this.outputStart++]; } } @Override public int read(final byte[] b, final int off, final int len) throws IOException { if (this.outputStart >= this.outputEnd) { this.refill(); } if (this.outputStart >= this.outputEnd) { return -1; } final int bytes = Math.min(len, this.outputEnd-this.outputStart); System.arraycopy(this.coder.output, this.outputStart, b, off, bytes); this.outputStart += bytes; return bytes; } /** * Read data from the input stream into inputBuffer, then * decode/encode it into the empty coder.output, and reset the * outputStart and outputEnd pointers. */ private void refill() throws IOException { if (this.eof) { return; } final int bytesRead = this.in.read(this.inputBuffer); boolean success; if (bytesRead == -1) { this.eof = true; success = this.coder.process(EMPTY, 0, 0, true); } else { success = this.coder.process(this.inputBuffer, 0, bytesRead, false); } if (!success) { throw new IOException("bad base-64"); } this.outputEnd = this.coder.op; this.outputStart = 0; } }
Java
package org.anddev.andengine.util; import org.anddev.andengine.util.pool.GenericPool; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 23:07:53 - 23.02.2011 */ public class TransformationPool { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static final GenericPool<Transformation> POOL = new GenericPool<Transformation>() { @Override protected Transformation onAllocatePoolItem() { return new Transformation(); } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== public static Transformation obtain() { return POOL.obtainPoolItem(); } public static void recycle(final Transformation pTransformation) { pTransformation.setToIdentity(); POOL.recyclePoolItem(pTransformation); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.net.Socket; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:42:15 - 18.09.2009 */ public class SocketUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static void closeSocket(final DatagramSocket pDatagramSocket) { if(pDatagramSocket != null && !pDatagramSocket.isClosed()) { pDatagramSocket.close(); } } public static void closeSocket(final Socket pSocket) { if(pSocket != null && !pSocket.isClosed()) { try { pSocket.close(); } catch (final IOException e) { Debug.e(e); } } } public static void closeSocket(final ServerSocket pServerSocket) { if(pServerSocket != null && !pServerSocket.isClosed()) { try { pServerSocket.close(); } catch (final IOException e) { Debug.e(e); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:52:44 - 03.01.2010 */ public interface Callable<T> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== /** * Computes a result, or throws an exception if unable to do so. * * @return the computed result. * @throws Exception if unable to compute a result. */ public T call() throws Exception; }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:35:42 - 01.05.2011 */ public class ArrayUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static <T> T random(final T[] pArray) { return pArray[MathUtils.random(0, pArray.length - 1)]; } public static void reverse(final byte[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; byte tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static void reverse(final short[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; short tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static void reverse(final int[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; int tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static void reverse(final long[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; long tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static void reverse(final float[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; float tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static void reverse(final double[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; double tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static void reverse(final Object[] pArray) { if (pArray == null) { return; } int i = 0; int j = pArray.length - 1; Object tmp; while (j > i) { tmp = pArray[j]; pArray[j] = pArray[i]; pArray[i] = tmp; j--; i++; } } public static boolean equals(final byte[] pArrayA, final int pOffsetA, final byte[] pArrayB, final int pOffsetB, final int pLength) { final int lastIndexA = pOffsetA + pLength; if(lastIndexA > pArrayA.length) { throw new ArrayIndexOutOfBoundsException(pArrayA.length); } final int lastIndexB = pOffsetB + pLength; if(lastIndexB > pArrayB.length) { throw new ArrayIndexOutOfBoundsException(pArrayB.length); } for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) { if(pArrayA[a] != pArrayB[b]) { return false; } } return true; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:01:08 - 03.04.2010 */ public class StringUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static String padFront(final String pString, final char pPadChar, final int pLength) { final int padCount = pLength - pString.length(); if(padCount <= 0) { return pString; } else { final StringBuilder sb = new StringBuilder(); for(int i = padCount - 1; i >= 0; i--) { sb.append(pPadChar); } sb.append(pString); return sb.toString(); } } public static int countOccurrences(final String pString, final char pCharacter) { int count = 0; int lastOccurrence = pString.indexOf(pCharacter, 0); while (lastOccurrence != -1) { count++; lastOccurrence = pString.indexOf(pCharacter, lastOccurrence + 1); } return count; } /** * Split a String by a Character, i.e. Split lines by using '\n'.<br/> * Same behavior as <code>String.split("" + pCharacter);</code> . * * @param pString * @param pCharacter * @return */ public static String[] split(final String pString, final char pCharacter) { return StringUtils.split(pString, pCharacter, null); } /** * Split a String by a Character, i.e. Split lines by using '\n'.<br/> * Same behavior as <code>String.split("" + pCharacter);</code> . * * @param pString * @param pCharacter * @param pReuse tries to reuse the String[] if the length is the same as the length needed. * @return */ public static String[] split(final String pString, final char pCharacter, final String[] pReuse) { final int partCount = StringUtils.countOccurrences(pString, pCharacter) + 1; final boolean reuseable = pReuse != null && pReuse.length == partCount; final String[] out = (reuseable) ? pReuse : new String[partCount]; if(partCount == 0) { out[0] = pString; } else { int from = 0; int to; for (int i = 0; i < partCount - 1; i++) { to = pString.indexOf(pCharacter, from); out[i] = pString.substring(from, to); from = to + 1; } out[partCount - 1] = pString.substring(from, pString.length()); } return out; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:48:13 - 03.09.2010 * @param <T> */ public abstract class BaseDurationModifier<T> extends BaseModifier<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private float mSecondsElapsed; protected final float mDuration; // =========================================================== // Constructors // =========================================================== public BaseDurationModifier(final float pDuration) { this.mDuration = pDuration; } public BaseDurationModifier(final float pDuration, final IModifierListener<T> pModifierListener) { super(pModifierListener); this.mDuration = pDuration; } protected BaseDurationModifier(final BaseDurationModifier<T> pBaseModifier) { this(pBaseModifier.mDuration); } // =========================================================== // Getter & Setter // =========================================================== @Override public float getSecondsElapsed() { return this.mSecondsElapsed; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getDuration() { return this.mDuration; } protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem); protected abstract void onManagedInitialize(final T pItem); @Override public final float onUpdate(final float pSecondsElapsed, final T pItem) { if(this.mFinished){ return 0; } else { if(this.mSecondsElapsed == 0) { this.onManagedInitialize(pItem); this.onModifierStarted(pItem); } final float secondsElapsedUsed; if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) { secondsElapsedUsed = pSecondsElapsed; } else { secondsElapsedUsed = this.mDuration - this.mSecondsElapsed; } this.mSecondsElapsed += secondsElapsedUsed; this.onManagedUpdate(secondsElapsedUsed, pItem); if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) { this.mSecondsElapsed = this.mDuration; this.mFinished = true; this.onModifierFinished(pItem); } return secondsElapsedUsed; } } @Override public void reset() { this.mFinished = false; this.mSecondsElapsed = 0; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier; import org.anddev.andengine.util.modifier.IModifier.IModifierListener; import org.anddev.andengine.util.modifier.util.ModifierUtils; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:39:25 - 19.03.2010 */ public class SequenceModifier<T> extends BaseModifier<T> implements IModifierListener<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private ISubSequenceModifierListener<T> mSubSequenceModifierListener; private final IModifier<T>[] mSubSequenceModifiers; private int mCurrentSubSequenceModifierIndex; private float mSecondsElapsed; private final float mDuration; private boolean mFinishedCached; // =========================================================== // Constructors // =========================================================== public SequenceModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException { this(null, null, pModifiers); } public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException { this(pSubSequenceModifierListener, null, pModifiers); } public SequenceModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException { this(null, pModifierListener, pModifiers); } public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException { super(pModifierListener); if (pModifiers.length == 0) { throw new IllegalArgumentException("pModifiers must not be empty!"); } this.mSubSequenceModifierListener = pSubSequenceModifierListener; this.mSubSequenceModifiers = pModifiers; this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers); pModifiers[0].addModifierListener(this); } @SuppressWarnings("unchecked") protected SequenceModifier(final SequenceModifier<T> pSequenceModifier) throws CloneNotSupportedException { this.mDuration = pSequenceModifier.mDuration; final IModifier<T>[] otherModifiers = pSequenceModifier.mSubSequenceModifiers; this.mSubSequenceModifiers = new IModifier[otherModifiers.length]; final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers; for(int i = shapeModifiers.length - 1; i >= 0; i--) { shapeModifiers[i] = otherModifiers[i].clone(); } shapeModifiers[0].addModifierListener(this); } @Override public SequenceModifier<T> clone() throws CloneNotSupportedException{ return new SequenceModifier<T>(this); } // =========================================================== // Getter & Setter // =========================================================== public ISubSequenceModifierListener<T> getSubSequenceModifierListener() { return this.mSubSequenceModifierListener; } public void setSubSequenceModifierListener(final ISubSequenceModifierListener<T> pSubSequenceModifierListener) { this.mSubSequenceModifierListener = pSubSequenceModifierListener; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getSecondsElapsed() { return this.mSecondsElapsed; } @Override public float getDuration() { return this.mDuration; } @Override public float onUpdate(final float pSecondsElapsed, final T pItem) { if(this.mFinished){ return 0; } else { float secondsElapsedRemaining = pSecondsElapsed; this.mFinishedCached = false; while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem); } this.mFinishedCached = false; final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; this.mSecondsElapsed += secondsElapsedUsed; return secondsElapsedUsed; } } @Override public void reset() { if(this.isFinished()) { this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this); } else { this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this); } this.mCurrentSubSequenceModifierIndex = 0; this.mFinished = false; this.mSecondsElapsed = 0; this.mSubSequenceModifiers[0].addModifierListener(this); final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers; for(int i = shapeModifiers.length - 1; i >= 0; i--) { shapeModifiers[i].reset(); } } @Override public void onModifierStarted(final IModifier<T> pModifier, final T pItem) { if(this.mCurrentSubSequenceModifierIndex == 0) { this.onModifierStarted(pItem); } if(this.mSubSequenceModifierListener != null) { this.mSubSequenceModifierListener.onSubSequenceStarted(pModifier, pItem, this.mCurrentSubSequenceModifierIndex); } } @Override public void onModifierFinished(final IModifier<T> pModifier, final T pItem) { if(this.mSubSequenceModifierListener != null) { this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex); } pModifier.removeModifierListener(this); this.mCurrentSubSequenceModifierIndex++; if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) { final IModifier<T> nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex]; nextSubSequenceModifier.addModifierListener(this); } else { this.mFinished = true; this.mFinishedCached = true; this.onModifierFinished(pItem); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public interface ISubSequenceModifierListener<T> { public void onSubSequenceStarted(final IModifier<T> pModifier, final T pItem, final int pIndex); public void onSubSequenceFinished(final IModifier<T> pModifier, final T pItem, final int pIndex); } }
Java
package org.anddev.andengine.util.modifier; import java.util.Comparator; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:17:50 - 19.03.2010 */ public interface IModifier<T> extends Cloneable { // =========================================================== // Final Fields // =========================================================== public static final Comparator<IModifier<?>> MODIFIER_COMPARATOR_DURATION_DESCENDING = new Comparator<IModifier<?>>() { @Override public int compare(final IModifier<?> pModifierA, final IModifier<?> pModifierB) { final float durationA = pModifierA.getDuration(); final float durationB = pModifierB.getDuration(); if (durationA < durationB) { return 1; } else if (durationA > durationB) { return -1; } else { return 0; } } }; // =========================================================== // Methods // =========================================================== public void reset(); public boolean isFinished(); public boolean isRemoveWhenFinished(); public void setRemoveWhenFinished(final boolean pRemoveWhenFinished); public IModifier<T> clone() throws CloneNotSupportedException; // public IModifier<T> clone(final IModifierListener<T> pModifierListener) throws CloneNotSupportedException; TODO public float getSecondsElapsed(); public float getDuration(); public float onUpdate(final float pSecondsElapsed, final T pItem); public void addModifierListener(final IModifierListener<T> pModifierListener); public boolean removeModifierListener(final IModifierListener<T> pModifierListener); // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IModifierListener<T> { // =========================================================== // Final Fields // =========================================================== // =========================================================== // Methods // =========================================================== public void onModifierStarted(final IModifier<T> pModifier, final T pItem); public void onModifierFinished(final IModifier<T> pModifier, final T pItem); } public static class CloneNotSupportedException extends RuntimeException { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = -5838035434002587320L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
Java
package org.anddev.andengine.util.modifier; import org.anddev.andengine.util.modifier.IModifier.IModifierListener; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:18:37 - 03.09.2010 * @param <T> */ public class LoopModifier<T> extends BaseModifier<T> implements IModifierListener<T> { // =========================================================== // Constants // =========================================================== public static final int LOOP_CONTINUOUS = -1; // =========================================================== // Fields // =========================================================== private float mSecondsElapsed; private final float mDuration; private final IModifier<T> mModifier; private ILoopModifierListener<T> mLoopModifierListener; private final int mLoopCount; private int mLoop; private boolean mModifierStartedCalled; private boolean mFinishedCached; // =========================================================== // Constructors // =========================================================== public LoopModifier(final IModifier<T> pModifier) { this(pModifier, LOOP_CONTINUOUS); } public LoopModifier(final IModifier<T> pModifier, final int pLoopCount) { this(pModifier, pLoopCount, null, (IModifierListener<T>)null); } public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final IModifierListener<T> pModifierListener) { this(pModifier, pLoopCount, null, pModifierListener); } public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener) { this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener<T>)null); } public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener, final IModifierListener<T> pModifierListener) { super(pModifierListener); this.mModifier = pModifier; this.mLoopCount = pLoopCount; this.mLoopModifierListener = pLoopModifierListener; this.mLoop = 0; this.mDuration = pLoopCount == LOOP_CONTINUOUS ? Float.POSITIVE_INFINITY : pModifier.getDuration() * pLoopCount; // TODO Check if POSITIVE_INFINITY works correct with i.e. SequenceModifier this.mModifier.addModifierListener(this); } protected LoopModifier(final LoopModifier<T> pLoopModifier) throws CloneNotSupportedException { this(pLoopModifier.mModifier.clone(), pLoopModifier.mLoopCount); } @Override public LoopModifier<T> clone() throws CloneNotSupportedException { return new LoopModifier<T>(this); } // =========================================================== // Getter & Setter // =========================================================== public ILoopModifierListener<T> getLoopModifierListener() { return this.mLoopModifierListener; } public void setLoopModifierListener(final ILoopModifierListener<T> pLoopModifierListener) { this.mLoopModifierListener = pLoopModifierListener; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getSecondsElapsed() { return this.mSecondsElapsed; } @Override public float getDuration() { return this.mDuration; } @Override public float onUpdate(final float pSecondsElapsed, final T pItem) { if(this.mFinished){ return 0; } else { float secondsElapsedRemaining = pSecondsElapsed; this.mFinishedCached = false; while(secondsElapsedRemaining > 0 && !this.mFinishedCached) { secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem); } this.mFinishedCached = false; final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining; this.mSecondsElapsed += secondsElapsedUsed; return secondsElapsedUsed; } } @Override public void reset() { this.mLoop = 0; this.mSecondsElapsed = 0; this.mModifierStartedCalled = false; this.mModifier.reset(); } // =========================================================== // Methods // =========================================================== @Override public void onModifierStarted(final IModifier<T> pModifier, final T pItem) { if(!this.mModifierStartedCalled) { this.mModifierStartedCalled = true; this.onModifierStarted(pItem); } if(this.mLoopModifierListener != null) { this.mLoopModifierListener.onLoopStarted(this, this.mLoop, this.mLoopCount); } } @Override public void onModifierFinished(final IModifier<T> pModifier, final T pItem) { if(this.mLoopModifierListener != null) { this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount); } if(this.mLoopCount == LOOP_CONTINUOUS) { this.mSecondsElapsed = 0; this.mModifier.reset(); } else { this.mLoop++; if(this.mLoop >= this.mLoopCount) { this.mFinished = true; this.mFinishedCached = true; this.onModifierFinished(pItem); } else { this.mSecondsElapsed = 0; this.mModifier.reset(); } } } // =========================================================== // Inner and Anonymous Classes // =========================================================== public interface ILoopModifierListener<T> { public void onLoopStarted(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount); public void onLoopFinished(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount); } }
Java
package org.anddev.andengine.util.modifier.util; import org.anddev.andengine.util.modifier.IModifier; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:16:36 - 03.09.2010 */ public class ModifierUtils { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static float getSequenceDurationOfModifier(final IModifier<?>[] pModifiers){ float duration = Float.MIN_VALUE; for(int i = pModifiers.length - 1; i >= 0; i--) { duration += pModifiers[i].getDuration(); } return duration; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier; import java.util.ArrayList; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.util.SmartList; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 14:34:57 - 03.09.2010 */ public class ModifierList<T> extends SmartList<IModifier<T>> implements IUpdateHandler { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = 1610345592534873475L; // =========================================================== // Fields // =========================================================== private final T mTarget; // =========================================================== // Constructors // =========================================================== public ModifierList(final T pTarget) { this.mTarget = pTarget; } public ModifierList(final T pTarget, final int pCapacity){ super(pCapacity); this.mTarget = pTarget; } // =========================================================== // Getter & Setter // =========================================================== public T getTarget() { return this.mTarget; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void onUpdate(final float pSecondsElapsed) { final ArrayList<IModifier<T>> modifiers = this; final int modifierCount = this.size(); if(modifierCount > 0) { for(int i = modifierCount - 1; i >= 0; i--) { final IModifier<T> modifier = modifiers.get(i); modifier.onUpdate(pSecondsElapsed, this.mTarget); if(modifier.isFinished() && modifier.isRemoveWhenFinished()) { modifiers.remove(i); } } } } @Override public void reset() { final ArrayList<IModifier<T>> modifiers = this; for(int i = modifiers.size() - 1; i >= 0; i--) { modifiers.get(i).reset(); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; import org.anddev.andengine.util.constants.MathConstants; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseSineIn implements IEaseFunction, MathConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseSineIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseSineIn() { } public static EaseSineIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseSineIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseSineIn.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return -FloatMath.cos(pPercentage * PI_HALF) + 1; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseExponentialOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseExponentialOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseExponentialOut() { } public static EaseExponentialOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseExponentialOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseExponentialOut.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return (pPercentage == 1) ? 1 : (-(float)Math.pow(2, -10 * pPercentage) + 1); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 17:13:17 - 26.07.2010 */ public interface IEaseFunction { // =========================================================== // Final Fields // =========================================================== public static final IEaseFunction DEFAULT = EaseLinear.getInstance(); // =========================================================== // Methods // =========================================================== public float getPercentage(final float pSecondsElapsed, final float pDuration); }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseQuartInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseQuartInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseQuartInOut() { } public static EaseQuartInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseQuartInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseQuartIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseQuartOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseQuadIn implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseQuadIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseQuadIn() { } public static EaseQuadIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseQuadIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseQuadIn.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return pPercentage * pPercentage; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseQuadInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseQuadInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseQuadInOut() { } public static EaseQuadInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseQuadInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseQuadIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseQuadOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseQuadOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseQuadOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseQuadOut() { } public static EaseQuadOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseQuadOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseQuadOut.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return -pPercentage * (pPercentage - 2); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseBackOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseBackOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseBackOut() { } public static EaseBackOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseBackOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseBackOut.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { final float t = pPercentage - 1; return 1 + t * t * ((1.70158f + 1) * t + 1.70158f); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseBounceInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseBounceInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseBounceInOut() { } public static EaseBounceInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseBounceInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseBounceIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseStrongOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseStrongOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseStrongOut() { } public static EaseStrongOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseStrongOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseStrongOut.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { final float t = pPercentage - 1; return 1 + (t * t * t * t * t); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseExponentialInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseExponentialInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseExponentialInOut() { } public static EaseExponentialInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseExponentialInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseExponentialIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseExponentialOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; import org.anddev.andengine.util.constants.MathConstants; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseElasticOut implements IEaseFunction, MathConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseElasticOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseElasticOut() { } public static EaseElasticOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseElasticOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseElasticOut.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentageDone) { if(pSecondsElapsed == 0) { return 0; } if(pSecondsElapsed == pDuration) { return 1; } final float p = pDuration * 0.3f; final float s = p / 4; return 1 + (float)Math.pow(2, -10 * pPercentageDone) * FloatMath.sin((pPercentageDone * pDuration - s) * PI_TWICE / p); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseCircularInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseCircularInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseCircularInOut() { } public static EaseCircularInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseCircularInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseCircularIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseCircularOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseCubicIn implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseCubicIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseCubicIn() { } public static EaseCubicIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseCubicIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseCubicIn.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return pPercentage * pPercentage * pPercentage; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseStrongIn implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseStrongIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseStrongIn() { } public static EaseStrongIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseStrongIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseStrongIn.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; import org.anddev.andengine.util.constants.MathConstants; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseSineOut implements IEaseFunction, MathConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseSineOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseSineOut() { } public static EaseSineOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseSineOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseSineOut.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return FloatMath.sin(pPercentage * PI_HALF); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseStrongInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseStrongInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseStrongInOut() { } public static EaseStrongInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseStrongInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseStrongIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseStrongOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseCircularIn implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseCircularIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseCircularIn() { } public static EaseCircularIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseCircularIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseCircularIn.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return -(FloatMath.sqrt(1 - pPercentage * pPercentage) - 1.0f); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseCubicInOut implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseCubicInOut INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseCubicInOut() { } public static EaseCubicInOut getInstance() { if(INSTANCE == null) { INSTANCE = new EaseCubicInOut(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { final float percentage = pSecondsElapsed / pDuration; if(percentage < 0.5f) { return 0.5f * EaseCubicIn.getValue(2 * percentage); } else { return 0.5f + 0.5f * EaseCubicOut.getValue(percentage * 2 - 1); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseQuintIn implements IEaseFunction { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseQuintIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseQuintIn() { } public static EaseQuintIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseQuintIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseQuintIn.getValue(pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pPercentage) { return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.util.modifier.ease; import org.anddev.andengine.util.constants.MathConstants; import android.util.FloatMath; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Gil * @author Nicolas Gramlich * @since 16:52:11 - 26.07.2010 */ public class EaseElasticIn implements IEaseFunction, MathConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private static EaseElasticIn INSTANCE; // =========================================================== // Constructors // =========================================================== private EaseElasticIn() { } public static EaseElasticIn getInstance() { if(INSTANCE == null) { INSTANCE = new EaseElasticIn(); } return INSTANCE; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public float getPercentage(final float pSecondsElapsed, final float pDuration) { return EaseElasticIn.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration); } // =========================================================== // Methods // =========================================================== public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentage) { if(pSecondsElapsed == 0) { return 0; } if(pSecondsElapsed == pDuration) { return 1; } final float p = pDuration * 0.3f; final float s = p / 4; final float t = pPercentage - 1; return -(float)Math.pow(2, 10 * t) * FloatMath.sin((t * pDuration - s) * PI_TWICE / p); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java