answer
stringlengths
17
10.2M
package nl.topicus.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.RowIdLifetime; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Types; import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement; public class CloudSpannerDatabaseMetaData extends AbstractCloudSpannerDatabaseMetaData { private static final int JDBC_MAJOR_VERSION = 4; private static final int JDBC_MINOR_VERSION = 2; private static final String FROM_STATEMENT_WITHOUT_RESULTS = " FROM INFORMATION_SCHEMA.TABLES WHERE 1=2 "; private static final String WHERE_1_EQUALS_1 = " WHERE 1=1 "; private static final String FROM_TABLES_T = " FROM INFORMATION_SCHEMA.TABLES AS T "; private CloudSpannerConnection connection; CloudSpannerDatabaseMetaData(CloudSpannerConnection connection) { this.connection = connection; } @Override public boolean allProceduresAreCallable() throws SQLException { return true; } @Override public boolean allTablesAreSelectable() throws SQLException { return true; } @Override public String getURL() throws SQLException { return connection.getUrl(); } @Override public String getUserName() throws SQLException { return connection.getClientId(); } @Override public boolean isReadOnly() throws SQLException { return false; } @Override public boolean nullsAreSortedHigh() throws SQLException { return false; } @Override public boolean nullsAreSortedLow() throws SQLException { return true; } @Override public boolean nullsAreSortedAtStart() throws SQLException { return false; } @Override public boolean nullsAreSortedAtEnd() throws SQLException { return false; } @Override public String getDatabaseProductName() throws SQLException { return connection.getProductName(); } @Override public String getDatabaseProductVersion() throws SQLException { return getDatabaseMajorVersion() + "." + getDatabaseMinorVersion(); } @Override public String getDriverName() throws SQLException { return CloudSpannerDriver.class.getName(); } @Override public String getDriverVersion() throws SQLException { return getDriverMajorVersion() + "." + getDriverMinorVersion(); } @Override public int getDriverMajorVersion() { return CloudSpannerDriver.MAJOR_VERSION; } @Override public int getDriverMinorVersion() { return CloudSpannerDriver.MINOR_VERSION; } @Override public boolean usesLocalFiles() throws SQLException { return false; } @Override public boolean usesLocalFilePerTable() throws SQLException { return false; } @Override public boolean supportsMixedCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesUpperCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesLowerCaseIdentifiers() throws SQLException { return false; } @Override public boolean storesMixedCaseIdentifiers() throws SQLException { return true; } @Override public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { return false; } @Override public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { return true; } @Override public String getIdentifierQuoteString() throws SQLException { return "`"; } @Override public String getSQLKeywords() throws SQLException { return "INTERLEAVE, PARENT"; } @Override public String getNumericFunctions() throws SQLException { return ""; } @Override public String getStringFunctions() throws SQLException { return ""; } @Override public String getSystemFunctions() throws SQLException { return ""; } @Override public String getTimeDateFunctions() throws SQLException { return ""; } @Override public String getSearchStringEscape() throws SQLException { return "\\"; } @Override public String getExtraNameCharacters() throws SQLException { return ""; } @Override public boolean supportsAlterTableWithAddColumn() throws SQLException { return true; } @Override public boolean supportsAlterTableWithDropColumn() throws SQLException { return true; } @Override public boolean supportsColumnAliasing() throws SQLException { return true; } @Override public boolean nullPlusNonNullIsNull() throws SQLException { return true; } @Override public boolean supportsConvert() throws SQLException { return false; } @Override public boolean supportsConvert(int fromType, int toType) throws SQLException { return false; } @Override public boolean supportsTableCorrelationNames() throws SQLException { return false; } @Override public boolean supportsDifferentTableCorrelationNames() throws SQLException { return false; } @Override public boolean supportsExpressionsInOrderBy() throws SQLException { return true; } @Override public boolean supportsOrderByUnrelated() throws SQLException { return true; } @Override public boolean supportsGroupBy() throws SQLException { return true; } @Override public boolean supportsGroupByUnrelated() throws SQLException { return true; } @Override public boolean supportsGroupByBeyondSelect() throws SQLException { return true; } @Override public boolean supportsLikeEscapeClause() throws SQLException { return true; } @Override public boolean supportsMultipleResultSets() throws SQLException { return false; } @Override public boolean supportsMultipleTransactions() throws SQLException { return true; } @Override public boolean supportsNonNullableColumns() throws SQLException { return true; } @Override public boolean supportsMinimumSQLGrammar() throws SQLException { return false; } @Override public boolean supportsCoreSQLGrammar() throws SQLException { return false; } @Override public boolean supportsExtendedSQLGrammar() throws SQLException { return false; } @Override public boolean supportsANSI92EntryLevelSQL() throws SQLException { return false; } @Override public boolean supportsANSI92IntermediateSQL() throws SQLException { return false; } @Override public boolean supportsANSI92FullSQL() throws SQLException { return false; } @Override public boolean supportsIntegrityEnhancementFacility() throws SQLException { return false; } @Override public boolean supportsOuterJoins() throws SQLException { return true; } @Override public boolean supportsFullOuterJoins() throws SQLException { return true; } @Override public boolean supportsLimitedOuterJoins() throws SQLException { return true; } @Override public String getSchemaTerm() throws SQLException { return null; } @Override public String getProcedureTerm() throws SQLException { return null; } @Override public String getCatalogTerm() throws SQLException { return null; } @Override public boolean isCatalogAtStart() throws SQLException { return false; } @Override public String getCatalogSeparator() throws SQLException { return null; } @Override public boolean supportsSchemasInDataManipulation() throws SQLException { return false; } @Override public boolean supportsSchemasInProcedureCalls() throws SQLException { return false; } @Override public boolean supportsSchemasInTableDefinitions() throws SQLException { return false; } @Override public boolean supportsSchemasInIndexDefinitions() throws SQLException { return false; } @Override public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; } @Override public boolean supportsCatalogsInProcedureCalls() throws SQLException { return false; } @Override public boolean supportsCatalogsInTableDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInIndexDefinitions() throws SQLException { return false; } @Override public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { return false; } @Override public boolean supportsPositionedDelete() throws SQLException { return false; } @Override public boolean supportsPositionedUpdate() throws SQLException { return false; } @Override public boolean supportsSelectForUpdate() throws SQLException { return false; } @Override public boolean supportsStoredProcedures() throws SQLException { return false; } @Override public boolean supportsSubqueriesInComparisons() throws SQLException { return true; } @Override public boolean supportsSubqueriesInExists() throws SQLException { return true; } @Override public boolean supportsSubqueriesInIns() throws SQLException { return true; } @Override public boolean supportsSubqueriesInQuantifieds() throws SQLException { return true; } @Override public boolean supportsCorrelatedSubqueries() throws SQLException { return true; } @Override public boolean supportsUnion() throws SQLException { return true; } @Override public boolean supportsUnionAll() throws SQLException { return true; } @Override public boolean supportsOpenCursorsAcrossCommit() throws SQLException { return false; } @Override public boolean supportsOpenCursorsAcrossRollback() throws SQLException { return false; } @Override public boolean supportsOpenStatementsAcrossCommit() throws SQLException { return false; } @Override public boolean supportsOpenStatementsAcrossRollback() throws SQLException { return false; } @Override public int getMaxBinaryLiteralLength() throws SQLException { return 0; } @Override public int getMaxCharLiteralLength() throws SQLException { return 0; } @Override public int getMaxColumnNameLength() throws SQLException { return 128; } @Override public int getMaxColumnsInGroupBy() throws SQLException { return 0; } @Override public int getMaxColumnsInIndex() throws SQLException { return 0; } @Override public int getMaxColumnsInOrderBy() throws SQLException { return 0; } @Override public int getMaxColumnsInSelect() throws SQLException { return 0; } @Override public int getMaxColumnsInTable() throws SQLException { return 0; } @Override public int getMaxConnections() throws SQLException { return 0; } @Override public int getMaxCursorNameLength() throws SQLException { return 0; } @Override public int getMaxIndexLength() throws SQLException { return 0; } @Override public int getMaxSchemaNameLength() throws SQLException { return 0; } @Override public int getMaxProcedureNameLength() throws SQLException { return 0; } @Override public int getMaxCatalogNameLength() throws SQLException { return 0; } @Override public int getMaxRowSize() throws SQLException { return 0; } @Override public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { return false; } @Override public int getMaxStatementLength() throws SQLException { return 0; } @Override public int getMaxStatements() throws SQLException { return 0; } @Override public int getMaxTableNameLength() throws SQLException { return 128; } @Override public int getMaxTablesInSelect() throws SQLException { return 0; } @Override public int getMaxUserNameLength() throws SQLException { return 0; } @Override public int getDefaultTransactionIsolation() throws SQLException { return Connection.TRANSACTION_SERIALIZABLE; } @Override public boolean supportsTransactions() throws SQLException { return true; } @Override public boolean supportsTransactionIsolationLevel(int level) throws SQLException { return Connection.TRANSACTION_SERIALIZABLE == level; } @Override public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { return false; } @Override public boolean supportsDataManipulationTransactionsOnly() throws SQLException { return true; } @Override public boolean dataDefinitionCausesTransactionCommit() throws SQLException { return true; } @Override public boolean dataDefinitionIgnoredInTransactions() throws SQLException { return false; } @Override public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, NULL AS RES1, NULL AS RES2, NULL AS RES3, " + "'' AS REMARKS, 0 AS PROCEDURE_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS PROCEDURE_CAT, '' AS PROCEDURE_SCHEM, '' AS PROCEDURE_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, " + "0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, " + "0 AS NULLABLE, '' AS REMARKS, '' AS COLUMN_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATATIME_SUB, " + "0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } private CloudSpannerPreparedStatement prepareStatement(String sql, String... params) throws SQLException { CloudSpannerPreparedStatement statement = connection.prepareStatement(sql); statement.setForceSingleUseReadContext(true); int paramIndex = 1; for (String param : params) { if (param != null) { statement.setString(paramIndex, param.toUpperCase()); paramIndex++; } } return statement; } @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { String sql = "select CASE WHEN TABLE_CATALOG='' THEN NULL ELSE TABLE_CATALOG END AS TABLE_CAT, CASE WHEN TABLE_SCHEMA='' THEN NULL ELSE TABLE_SCHEMA END AS TABLE_SCHEM, TABLE_NAME, 'TABLE' AS TABLE_TYPE, NULL AS REMARKS, NULL AS TYPE_CAT, NULL AS TYPE_SCHEM, NULL AS TYPE_NAME, NULL AS SELF_REFERENCING_COL_NAME, NULL AS REF_GENERATION " + FROM_TABLES_T + WHERE_1_EQUALS_1; if (catalog != null) sql = sql + "AND UPPER(T.TABLE_CATALOG) like ? "; if (schemaPattern != null) sql = sql + "AND UPPER(T.TABLE_SCHEMA) like ? "; if (tableNamePattern != null) sql = sql + "AND UPPER(T.TABLE_NAME) like ? "; sql = sql + "ORDER BY TABLE_NAME"; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern); return statement.executeQuery(); } @Override public ResultSet getSchemas() throws SQLException { String sql = "SELECT '' AS TABLE_SCHEM, '' AS TABLE_CAT " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getCatalogs() throws SQLException { String sql = "SELECT '' AS TABLE_CAT " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getTableTypes() throws SQLException { String sql = "SELECT 'TABLE' AS TABLE_TYPE"; return prepareStatement(sql).executeQuery(); } @Override public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { String sql = "select TABLE_CATALOG AS TABLE_CAT, TABLE_SCHEMA AS TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, " + "CASE " + " WHEN SPANNER_TYPE LIKE 'ARRAY%' THEN " + Types.ARRAY + " " + " WHEN SPANNER_TYPE = 'BOOL' THEN " + Types.BOOLEAN + " " + " WHEN SPANNER_TYPE LIKE 'BYTES%' THEN " + Types.BINARY + " " + " WHEN SPANNER_TYPE = 'DATE' THEN " + Types.DATE + " " + " WHEN SPANNER_TYPE = 'FLOAT64' THEN " + Types.DOUBLE + " " + " WHEN SPANNER_TYPE = 'INT64' THEN " + Types.BIGINT + " " + " WHEN SPANNER_TYPE LIKE 'STRING%' THEN " + Types.NVARCHAR + " " + " WHEN SPANNER_TYPE LIKE 'STRUCT%' THEN " + Types.STRUCT + " " + " WHEN SPANNER_TYPE = 'TIMESTAMP' THEN " + Types.TIMESTAMP + " " + "END AS DATA_TYPE, " + "SPANNER_TYPE AS TYPE_NAME, " + "CASE " + "WHEN strpos(spanner_type, '(')=0 then 0 " + "ELSE cast(replace(substr(spanner_type, strpos(spanner_type, '(')+1, strpos(spanner_type, ')')-strpos(spanner_type, '(')-1), 'MAX', '0') as INT64) " + "END AS COLUMN_SIZE, " + "0 AS BUFFER_LENGTH, NULL AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, " + "CASE " + " WHEN IS_NULLABLE = 'YES' THEN 1 " + " WHEN IS_NULLABLE = 'NO' THEN 0 " + " ELSE 2 " + "END AS NULLABLE, NULL AS REMARKS, NULL AS COLUMN_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATETIME_SUB, 0 AS CHAR_OCTET_LENGTH, ORDINAL_POSITION, IS_NULLABLE, NULL AS SCOPE_CATALOG, " + "NULL AS SCOPE_SCHEMA, NULL AS SCOPE_TABLE, NULL AS SOURCE_DATA_TYPE, 'NO' AS IS_AUTOINCREMENT, 'NO' AS IS_GENERATEDCOLUMN " + "FROM information_schema.columns " + WHERE_1_EQUALS_1; if (catalog != null) sql = sql + "AND UPPER(TABLE_CATALOG) like ? "; if (schemaPattern != null) sql = sql + "AND UPPER(TABLE_SCHEMA) like ? "; if (tableNamePattern != null) sql = sql + "AND UPPER(TABLE_NAME) like ? "; if (columnNamePattern != null) sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? "; sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern, columnNamePattern); return statement.executeQuery(); } @Override public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS COLUMN_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS GRANTOR, '' AS GRANTEE, '' AS PRIVILEGE, 'NO' AS IS_GRANTABLE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { String sql = "SELECT 0 AS SCOPE, '' AS COLUMN_NAME, 0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS COLUMN_SIZE, 0 AS BUFFER_LENGTH, " + "0 AS DECIMAL_DIGITS, 0 AS PSEUDO_COLUMN " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { String sql = "SELECT 0 AS SCOPE, '' AS COLUMN_NAME, 0 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS COLUMN_SIZE, 0 AS BUFFER_LENGTH, " + "0 AS DECIMAL_DIGITS, 0 AS PSEUDO_COLUMN " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT IDX.TABLE_CATALOG AS TABLE_CAT, IDX.TABLE_SCHEMA AS TABLE_SCHEM, IDX.TABLE_NAME AS TABLE_NAME, COLS.COLUMN_NAME AS COLUMN_NAME, ORDINAL_POSITION AS KEY_SEQ, IDX.INDEX_NAME AS PK_NAME " + "FROM INFORMATION_SCHEMA.INDEXES IDX " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COLS ON IDX.TABLE_CATALOG=COLS.TABLE_CATALOG AND IDX.TABLE_SCHEMA=COLS.TABLE_SCHEMA AND IDX.TABLE_NAME=COLS.TABLE_NAME AND IDX.INDEX_NAME=COLS.INDEX_NAME " + "WHERE IDX.INDEX_TYPE='PRIMARY_KEY' "; if (catalog != null) sql = sql + "AND UPPER(IDX.TABLE_CATALOG) like ? "; if (schema != null) sql = sql + "AND UPPER(IDX.TABLE_SCHEMA) like ? "; if (table != null) sql = sql + "AND UPPER(IDX.TABLE_NAME) like ? "; sql = sql + "ORDER BY COLS.ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT PARENT.TABLE_CATALOG AS PKTABLE_CAT, PARENT.TABLE_SCHEMA AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, COL.COLUMN_NAME AS PKCOLUMN_NAME, CHILD.TABLE_CATALOG AS FKTABLE_CAT, CHILD.TABLE_SCHEMA AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, COL.COLUMN_NAME FKCOLUMN_NAME, COL.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION = 'CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, NULL AS FK_NAME, INDEXES.INDEX_NAME AS PK_NAME, 7 AS DEFERRABILITY " + "FROM INFORMATION_SCHEMA.TABLES CHILD " + "INNER JOIN INFORMATION_SCHEMA.TABLES PARENT ON CHILD.TABLE_CATALOG=PARENT.TABLE_CATALOG AND CHILD.TABLE_SCHEMA=PARENT.TABLE_SCHEMA AND CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME " + "INNER JOIN INFORMATION_SCHEMA.INDEXES ON PARENT.TABLE_CATALOG=INDEXES.TABLE_CATALOG AND PARENT.TABLE_SCHEMA=INDEXES.TABLE_SCHEMA AND PARENT.TABLE_NAME=INDEXES.TABLE_NAME AND INDEXES.INDEX_TYPE='PRIMARY_KEY' " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS COL ON INDEXES.TABLE_CATALOG=COL.TABLE_CATALOG AND INDEXES.TABLE_SCHEMA=COL.TABLE_SCHEMA AND INDEXES.TABLE_NAME=COL.TABLE_NAME AND INDEXES.INDEX_NAME=COL.INDEX_NAME " + "WHERE CHILD.PARENT_TABLE_NAME IS NOT NULL "; if (catalog != null) sql = sql + "AND UPPER(CHILD.TABLE_CATALOG) like ? "; if (schema != null) sql = sql + "AND UPPER(CHILD.TABLE_SCHEMA) like ? "; if (table != null) sql = sql + "AND UPPER(CHILD.TABLE_NAME) like ? "; sql = sql + "ORDER BY PARENT.TABLE_CATALOG, PARENT.TABLE_SCHEMA, PARENT.TABLE_NAME, COL.ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { String sql = "SELECT " + "NULL AS PKTABLE_CAT, NULL AS PKTABLE_SCHEM, PARENT.TABLE_NAME AS PKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS PKCOLUMN_NAME, " + "NULL AS FKTABLE_CAT, NULL AS FKTABLE_SCHEM, CHILD.TABLE_NAME AS FKTABLE_NAME, PARENT_INDEX_COLUMNS.COLUMN_NAME AS FKCOLUMN_NAME, " + "PARENT_INDEX_COLUMNS.ORDINAL_POSITION AS KEY_SEQ, 3 AS UPDATE_RULE, CASE WHEN CHILD.ON_DELETE_ACTION='CASCADE' THEN 0 ELSE 3 END AS DELETE_RULE, " + "NULL AS FK_NAME, 'PRIMARY_KEY' AS PK_NAME, 7 AS DEFERRABILITY " + "FROM INFORMATION_SCHEMA.TABLES PARENT " + "INNER JOIN INFORMATION_SCHEMA.TABLES CHILD ON CHILD.PARENT_TABLE_NAME=PARENT.TABLE_NAME " + "INNER JOIN INFORMATION_SCHEMA.INDEX_COLUMNS PARENT_INDEX_COLUMNS ON PARENT_INDEX_COLUMNS.TABLE_NAME=PARENT.TABLE_NAME AND PARENT_INDEX_COLUMNS.INDEX_NAME='PRIMARY_KEY' " + WHERE_1_EQUALS_1; if (catalog != null) sql = sql + "AND UPPER(PARENT.TABLE_CATALOG) like ? "; if (schema != null) sql = sql + "AND UPPER(PARENT.TABLE_SCHEMA) like ? "; if (table != null) sql = sql + "AND UPPER(PARENT.TABLE_NAME) like ? "; sql = sql + "ORDER BY CHILD.TABLE_CATALOG, CHILD.TABLE_SCHEMA, CHILD.TABLE_NAME, PARENT_INDEX_COLUMNS.ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public ResultSet getTypeInfo() throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { String sql = "select idx.TABLE_CATALOG AS TABLE_CAT, idx.TABLE_SCHEMA AS TABLE_SCHEM, idx.TABLE_NAME, CASE WHEN IS_UNIQUE THEN FALSE ELSE TRUE END AS NON_UNIQUE, NULL AS INDEX_QUALIFIER, idx.INDEX_NAME, 3 AS TYPE, ORDINAL_POSITION, COLUMN_NAME, SUBSTR(COLUMN_ORDERING, 0, 1) AS ASC_OR_DESC, -1 AS CARDINALITY, -1 AS PAGES, NULL AS FILTER_CONDITION " + "FROM information_schema.indexes idx " + "INNER JOIN information_schema.index_columns col on idx.table_catalog=col.table_catalog and idx.table_schema=col.table_schema and idx.table_name=col.table_name and idx.index_name=col.index_name " + WHERE_1_EQUALS_1; if (catalog != null) sql = sql + "AND UPPER(idx.TABLE_CATALOG) like ? "; if (schema != null) sql = sql + "AND UPPER(idx.TABLE_SCHEMA) like ? "; if (table != null) sql = sql + "AND UPPER(idx.TABLE_NAME) like ? "; if (unique) sql = sql + "AND IS_UNIQUE "; sql = sql + "ORDER BY IS_UNIQUE, INDEX_NAME, ORDINAL_POSITION "; PreparedStatement statement = prepareStatement(sql, catalog, schema, table); return statement.executeQuery(); } @Override public boolean supportsResultSetType(int type) throws SQLException { return type == ResultSet.TYPE_FORWARD_ONLY; } @Override public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY; } @Override public boolean ownUpdatesAreVisible(int type) throws SQLException { return false; } @Override public boolean ownDeletesAreVisible(int type) throws SQLException { return false; } @Override public boolean ownInsertsAreVisible(int type) throws SQLException { return false; } @Override public boolean othersUpdatesAreVisible(int type) throws SQLException { return false; } @Override public boolean othersDeletesAreVisible(int type) throws SQLException { return false; } @Override public boolean othersInsertsAreVisible(int type) throws SQLException { return false; } @Override public boolean updatesAreDetected(int type) throws SQLException { return false; } @Override public boolean deletesAreDetected(int type) throws SQLException { return false; } @Override public boolean insertsAreDetected(int type) throws SQLException { return false; } @Override public boolean supportsBatchUpdates() throws SQLException { return false; } @Override public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public Connection getConnection() throws SQLException { return connection; } @Override public boolean supportsSavepoints() throws SQLException { return false; } @Override public boolean supportsNamedParameters() throws SQLException { return true; } @Override public boolean supportsMultipleOpenResults() throws SQLException { return false; } @Override public boolean supportsGetGeneratedKeys() throws SQLException { return false; } @Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { String sql = "SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, " + "'' AS SUPERTYPE_CAT, '' AS SUPERTYPE_SCHEM, '' AS SUPERTYPE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { String sql = "SELECT '' AS TABLE_CAT, '' AS TABLE_SCHEM, '' AS TABLE_NAME, '' AS SUPERTABLE_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { String sql = "SELECT '' AS TYPE_CAT, '' AS TYPE_SCHEM, '' AS TYPE_NAME, '' AS ATTR_NAME, 0 AS DATA_TYPE, " + "'' AS ATTR_TYPE_NAME, 0 AS ATTR_SIZE, 0 AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 0 AS NULLABLE, " + "'' AS REMARKS, '' AS ATTR_DEF, 0 AS SQL_DATA_TYPE, 0 AS SQL_DATETIME_SUB, 0 AS CHAR_OCTET_LENGTH, " + "0 AS ORDINAL_POSITION, 'NO' AS IS_NULLABLE, '' AS SCOPE_CATALOG, '' AS SCOPE_SCHEMA, '' AS SCOPE_TABLE, " + "0 AS SOURCE_DATA_TYPE " + FROM_STATEMENT_WITHOUT_RESULTS; CloudSpannerPreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public boolean supportsResultSetHoldability(int holdability) throws SQLException { return holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT; } @Override public int getResultSetHoldability() throws SQLException { return ResultSet.CLOSE_CURSORS_AT_COMMIT; } @Override public int getDatabaseMajorVersion() throws SQLException { return 1; } @Override public int getDatabaseMinorVersion() throws SQLException { return 0; } @Override public int getJDBCMajorVersion() throws SQLException { return JDBC_MAJOR_VERSION; } @Override public int getJDBCMinorVersion() throws SQLException { return JDBC_MINOR_VERSION; } @Override public int getSQLStateType() throws SQLException { return sqlStateSQL; } @Override public boolean locatorsUpdateCopy() throws SQLException { return false; } @Override public boolean supportsStatementPooling() throws SQLException { return false; } @Override public RowIdLifetime getRowIdLifetime() throws SQLException { return RowIdLifetime.ROWID_UNSUPPORTED; } @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { String sql = "SELECT '' AS TABLE_SCHEM, '' AS TABLE_CATALOG " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY TABLE_SCHEM "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { return false; } @Override public boolean autoCommitFailureClosesAllResultSets() throws SQLException { return false; } @Override public ResultSet getClientInfoProperties() throws SQLException { String sql = "SELECT '' AS NAME, 0 AS MAX_LEN, '' AS DEFAULT_VALUE, '' AS DESCRIPTION " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { String sql = "SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS REMARKS, 0 AS FUNCTION_TYPE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { String sql = "SELECT '' AS FUNCTION_CAT, '' AS FUNCTION_SCHEM, '' AS FUNCTION_NAME, '' AS COLUMN_NAME, 0 AS COLUMN_TYPE, 1111 AS DATA_TYPE, '' AS TYPE_NAME, 0 AS PRECISION, 0 AS LENGTH, 0 AS SCALE, 0 AS RADIX, 0 AS NULLABLE, '' AS REMARKS, 0 AS CHAR_OCTET_LENGTH, 0 AS ORDINAL_POSITION, '' AS IS_NULLABLE, '' AS SPECIFIC_NAME " + FROM_STATEMENT_WITHOUT_RESULTS; sql = sql + " ORDER BY FUNCTION_CAT, FUNCTION_SCHEM, FUNCTION_NAME, SPECIFIC_NAME "; PreparedStatement statement = prepareStatement(sql); return statement.executeQuery(); } @Override public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { String sql = "select TABLE_CATALOG AS TABLE_CAT, TABLE_SCHEMA AS TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, " + "CASE " + " WHEN SPANNER_TYPE = 'ARRAY' THEN " + Types.ARRAY + " " + " WHEN SPANNER_TYPE = 'BOOL' THEN " + Types.BOOLEAN + " " + " WHEN SPANNER_TYPE = 'BYTES' THEN " + Types.BINARY + " " + " WHEN SPANNER_TYPE = 'DATE' THEN " + Types.DATE + " " + " WHEN SPANNER_TYPE = 'FLOAT64' THEN " + Types.DOUBLE + " " + " WHEN SPANNER_TYPE = 'INT64' THEN " + Types.BIGINT + " " + " WHEN SPANNER_TYPE = 'STRING' THEN " + Types.NVARCHAR + " " + " WHEN SPANNER_TYPE = 'STRUCT' THEN " + Types.STRUCT + " " + " WHEN SPANNER_TYPE = 'TIMESTAMP' THEN " + Types.TIMESTAMP + " " + "END AS DATA_TYPE, " + "0 AS COLUMN_SIZE, NULL AS DECIMAL_DIGITS, 0 AS NUM_PREC_RADIX, 'USAGE_UNKNOWN' AS COLUMN_USAGE, NULL AS REMARKS, 0 AS CHAR_OCTET_LENGTH, IS_NULLABLE " + FROM_STATEMENT_WITHOUT_RESULTS; if (catalog != null) sql = sql + "AND UPPER(TABLE_CATALOG) like ? "; if (schemaPattern != null) sql = sql + "AND UPPER(TABLE_SCHEMA) like ? "; if (tableNamePattern != null) sql = sql + "AND UPPER(TABLE_NAME) like ? "; if (columnNamePattern != null) sql = sql + "AND UPPER(COLUMN_NAME) LIKE ? "; sql = sql + "ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION "; CloudSpannerPreparedStatement statement = prepareStatement(sql, catalog, schemaPattern, tableNamePattern, columnNamePattern); return statement.executeQuery(); } @Override public boolean generatedKeyAlwaysReturned() throws SQLException { return false; } }
package org.ambraproject.wombat.config.site.url; import com.google.common.base.Preconditions; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; import org.ambraproject.wombat.config.site.RequestMappingContext; import org.ambraproject.wombat.config.site.RequestMappingContextDictionary; import org.ambraproject.wombat.config.site.Site; import org.ambraproject.wombat.config.site.SiteSet; import org.ambraproject.wombat.util.ClientEndpoint; import org.ambraproject.wombat.util.UrlParamBuilder; import org.springframework.http.HttpStatus; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import org.springframework.web.servlet.view.RedirectView; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A link to a site page. * <p> * An instance of this class encapsulates a path to the linked page and the site to which the linked page belongs. It * depends on an {@code HttpServletRequest} object in order to build an {@code href} value to appear in the * corresponding response. */ public class Link { private final Optional<Site> site; // absent if the path is for a siteless handler private final String path; private final boolean isAbsolute; private Link(Optional<Site> site, String path, boolean isAbsolute) { this.site = Preconditions.checkNotNull(site); this.path = Preconditions.checkNotNull(path); this.isAbsolute = isAbsolute; } /** * Begin building a link to a page within the same site. * * @param localSite the site for both the originating page and the link target */ public static Factory toLocalSite(Site localSite) { return new Factory(Optional.of(localSite), false); } /** * Begin building a link to an absolute address. * <p> * This should be used only if the resulting link will appear in a context outside of a local site, such as in a * downloadable document file. If the link will appear on a site page served by this application, instead use {@link * #toLocalSite} or {@link #toForeignSite} with a correct {@code localSite} argument. * * @param targetSite the site of the link target */ public static Factory toAbsoluteAddress(Site targetSite) { return new Factory(Optional.of(targetSite), true); } /** * Begin building a link to a page on another site. * * @param localSite the site of the originating page * @param foreignSite the site of the link target */ public static Factory toForeignSite(Site localSite, Site foreignSite) { Optional<String> localHostname = localSite.getRequestScheme().getHostName(); Optional<String> foreignHostname = foreignSite.getRequestScheme().getHostName(); final boolean isAbsolute; if (foreignHostname.isPresent()) { isAbsolute = !localHostname.equals(foreignHostname); } else if (!localHostname.isPresent()) { isAbsolute = false; } else { throw new RuntimeException(String.format("" + "Cannot link to a site with no configured hostname (%s) from a site with one (%s; hostname=%s). " + "(Note: This error can be prevented by configuring a hostname either on every site or none.)", foreignSite.getKey(), localSite.getKey(), localHostname.get())); } return new Factory(Optional.of(foreignSite), isAbsolute); } /** * Begin building a link to a siteless handler. The returned factory object will throw exceptions if {@link * Factory#toPattern} is called for a handler that is not siteless, and will silently link to any path with no site * token if {@link Factory#toPath} is called. * * @see org.ambraproject.wombat.config.site.Siteless */ public static Factory toSitelessHandler() { return SITELESS_FACTORY; } private static final Factory SITELESS_FACTORY = new Factory(Optional.empty(), true); /** * Begin building a link to a page on another site. * * @param localSite the site of the originating page * @param foreignJournalKey the journal key of the target site * @param siteSet the global site set */ public static Factory toForeignSite(Site localSite, String foreignJournalKey, SiteSet siteSet) { Site foreignSite = localSite.getTheme().resolveForeignJournalKey(siteSet, foreignJournalKey); return toForeignSite(localSite, foreignSite); } /** * An intermediate builder class. */ public static class Factory { private final Optional<Site> site; // if absent, may link only to siteless handlers private final boolean isAbsolute; private Factory(Optional<Site> site, boolean isAbsolute) { this.site = Preconditions.checkNotNull(site); this.isAbsolute = isAbsolute; } /** * Build a link to a direct path. * * @param path the path to link to */ public Link toPath(String path) { return new Link(site, path, isAbsolute); } /** * Build a link that will hit a specified request handler. * * @param requestMappingContextDictionary the global handler directory * @param handlerName the name of the target request handler * @param variables values to fill in to path variables in the request handler's pattern * @param queryParameters query parameters to add to the end of the URL * @param wildcardValues values to substitute for wildcards in the request handler's pattern */ public Link toPattern(RequestMappingContextDictionary requestMappingContextDictionary, String handlerName, Map<String, ?> variables, Multimap<String, ?> queryParameters, List<?> wildcardValues) { RequestMappingContext mapping = requestMappingContextDictionary.getPattern(handlerName, site.orElse(null)); if (mapping == null) { String message = site.isPresent() ? String.format("No handler with name=\"%s\" exists for site: %s", handlerName, site.get().getKey()) : String.format("No siteless handler with name=\"%s\" exists", handlerName); throw new PatternNotFoundException(message); } final Optional<Site> linkSite; if (mapping.isSiteless()) { linkSite = Optional.empty(); } else if (site.isPresent()) { linkSite = site; } else { throw new IllegalStateException("Can link only to Siteless handlers with a 'toSitelessHandler' Factory"); } String path = buildPathFromPattern(mapping.getPattern(), linkSite, variables, queryParameters, wildcardValues); return new Link(linkSite, path, isAbsolute); } public PatternBuilder toPattern(RequestMappingContextDictionary requestMappingContextDictionary, String handlerName) { return new PatternBuilder(requestMappingContextDictionary, handlerName); } public class PatternBuilder { private final RequestMappingContextDictionary requestMappingContextDictionary; private final String handlerName; private final Map<String, Object> pathVariables = new LinkedHashMap<>(); private final Multimap<String, Object> queryParameters = LinkedListMultimap.create(); private final List<Object> wildcardValues = new ArrayList<>(); private PatternBuilder(RequestMappingContextDictionary requestMappingContextDictionary, String handlerName) { this.requestMappingContextDictionary = Objects.requireNonNull(requestMappingContextDictionary); this.handlerName = Objects.requireNonNull(handlerName); } public PatternBuilder addPathVariables(Map<String, ?> pathVariables) { this.pathVariables.putAll(pathVariables); return this; } public PatternBuilder addPathVariable(String key, Object value) { this.pathVariables.put(key, value); return this; } public PatternBuilder addQueryParameters(Map<String, ?> queryParameters) { queryParameters.forEach(this.queryParameters::put); return this; } public PatternBuilder addQueryParameters(Multimap<String, ?> queryParameters) { this.queryParameters.putAll(queryParameters); return this; } public PatternBuilder addQueryParameter(String key, Object value) { this.queryParameters.put(key, value); return this; } public PatternBuilder addWildcardValues(List<?> wildcardValues) { this.wildcardValues.addAll(wildcardValues); return this; } public PatternBuilder addWildcardValue(Object wildcardValue) { this.wildcardValues.add(wildcardValue); return this; } public Link build() { return toPattern(requestMappingContextDictionary, handlerName, pathVariables, queryParameters, wildcardValues); } } } public static class PatternNotFoundException extends RuntimeException { private PatternNotFoundException(String message) { super(message); } } // Match path wildcards of one or two asterisks private static final Pattern WILDCARD = Pattern.compile("\\*\\*?"); private static String buildPathFromPattern(String pattern, Optional<Site> site, Map<String, ?> variables, Multimap<String, ?> queryParameters, List<?> wildcardValues) { Preconditions.checkNotNull(site); Preconditions.checkNotNull(variables); Preconditions.checkNotNull(queryParameters); if (site.isPresent() && site.get().getRequestScheme().hasPathToken()) { if (pattern.equals("/*") || pattern.startsWith("/*/")) { pattern = pattern.substring(2); } else { throw new RuntimeException("Pattern is inconsistent with site's request scheme"); } } String path = fillVariables(pattern, variables); path = fillWildcardValues(path, wildcardValues); path = appendQueryParameters(queryParameters, path); return path; } private static String fillVariables(String path, final Map<String, ?> variables) { UriComponentsBuilder builder = ServletUriComponentsBuilder.fromPath(path); UriComponents.UriTemplateVariables uriVariables = (String name) -> { Object value = variables.get(name); if (value == null) { throw new IllegalArgumentException("Missing required parameter " + name); } return value; }; return builder.build().expand(uriVariables).encode().toString(); } private static String fillWildcardValues(String path, List<?> wildcardValues) { Matcher matcher = WILDCARD.matcher(path); boolean hasAtLeastOneWildcard = matcher.find(); if (!hasAtLeastOneWildcard) { if (wildcardValues.isEmpty()) { return path; } else { throw complainAboutNumberOfWildcards(path, wildcardValues); } } StringBuffer filled = new StringBuffer(path.length() * 2); Iterator<?> valueIterator = wildcardValues.iterator(); do { if (!valueIterator.hasNext()) throw complainAboutNumberOfWildcards(path, wildcardValues); String wildcardValue = valueIterator.next().toString(); if (!matcher.group().equals("**") && wildcardValue.contains("/")) { String message = String.format("Cannot fill a multi-token value into a single-token wildcard. Value: \"%s\" Path: \"%s\"", wildcardValue, path); throw new IllegalArgumentException(message); } matcher.appendReplacement(filled, wildcardValue); } while (matcher.find()); if (valueIterator.hasNext()) throw complainAboutNumberOfWildcards(path, wildcardValues); matcher.appendTail(filled); return filled.toString(); } private static IllegalArgumentException complainAboutNumberOfWildcards(String path, List<?> wildcardValues) { int wildcardCount = 0; Matcher matcher = WILDCARD.matcher(path); while (matcher.find()) { wildcardCount++; } String message = String.format("Path has %d wildcard%s but was supplied %d value%s. Path=\"%s\" Values=%s", wildcardCount, (wildcardCount == 1 ? "" : "s"), wildcardValues.size(), (wildcardValues.size() == 1 ? "" : "s"), path, wildcardValues.toString()); return new IllegalArgumentException(message); } private static String appendQueryParameters(Multimap<String, ?> queryParameters, String path) { if (!queryParameters.isEmpty()) { UrlParamBuilder paramBuilder = UrlParamBuilder.params(); for (Map.Entry<String, ?> paramEntry : queryParameters.entries()) { paramBuilder.add(paramEntry.getKey(), paramEntry.getValue().toString()); } path = path + "?" + paramBuilder.format(); } return path; } /** * Build a Spring view string that which, if returned from a Spring {@code RequestMapping} method, will redirect to * the linked address. * * @param request the originating request of the page from which to link * @return a Spring redirect string */ public RedirectView getRedirect(HttpServletRequest request) { RedirectView redirectView = new RedirectView(get(request)); redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); return redirectView; } /** * Build a link from this object. The returned value may be either an absolute link (full URL) or a relative link * (path beginning with "/") depending on the sites used to set up this object. * <p> * The returned path is suitable as an {@code href} value to be used in the response to the {@code request} argument. * The argument value must resolve to the local site given to set up this object. * * @param request the originating request of the page from which to link * @return a page that links from the originating page to the target page */ public String get(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); if (isAbsolute) { appendPrefix(sb, request); } sb.append(request.getContextPath()).append('/'); Optional<String> pathToken = site.flatMap(s -> s.getRequestScheme().getPathToken()); if (pathToken.isPresent()) { sb.append(pathToken.get()).append('/'); } String path = this.path.startsWith("/") ? this.path.substring(1) : this.path; sb.append(path); return sb.toString(); } private void appendPrefix(StringBuilder sb, HttpServletRequest request) { String protocol = request.getHeader("X-Forwarded-Proto"); protocol = protocol == null ? "http" : protocol; sb.append(protocol).append(": ClientEndpoint clientEndpoint = ClientEndpoint.get(request); Optional<String> targetHostname = site.flatMap(s -> s.getRequestScheme().getHostName()); sb.append(targetHostname.orElse(clientEndpoint.getHostname())); clientEndpoint.getPort().ifPresent(serverPort -> { sb.append(':').append(serverPort); }); } @Override public String toString() { return "Link{" + "site=" + site + ", path='" + path + '\'' + ", isAbsolute=" + isAbsolute + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Link link = (Link) o; if (isAbsolute != link.isAbsolute) return false; if (!path.equals(link.path)) return false; if (!site.equals(link.site)) return false; return true; } @Override public int hashCode() { int result = site.hashCode(); result = 31 * result + path.hashCode(); result = 31 * result + (isAbsolute ? 1 : 0); return result; } }
package nl.pvanassen.ns.model.stations; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import nl.pvanassen.ns.handle.Handle; import nl.pvanassen.ns.xml.Xml; public class StationsHandle implements Handle<Stations> { @Override public Stations getModel(InputStream stream) { List<Station> stations = new LinkedList<Station>(); Xml xml = Xml.getXml(stream, "Stations"); for (Xml stationXml : xml.children("Station")) { String code = stationXml.child("Code").content(); String type = stationXml.child("Type").content(); Namen namen = new Namen(stationXml.child("Namen").child("Kort").content(), stationXml.child("Namen") .child("Middel").content(), stationXml.child("Namen").child("Lang").content()); String land = stationXml.child("Land").content(); int uicCode = Integer.parseInt(stationXml.child("UICCode").content()); double lat = Double.parseDouble(stationXml.child("Lat").content()); double lon = Double.parseDouble(stationXml.child("Lon").content()); List<String> synoniemen = new ArrayList<String>(stationXml.child("Synoniemen").children("Synoniem").size()); for (Xml synomiemXml : stationXml.child("Synoniemen").children("Synoniem")) { synoniemen.add(synomiemXml.content()); } stations.add(new Station(code, type, namen, land, uicCode, lat, lon, synoniemen)); } return new Stations(stations); } }
package org.animotron.graph.traverser; import org.animotron.Properties; import org.animotron.graph.handler.GraphHandler; import org.animotron.manipulator.PFlow; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.ml.NAME; import org.animotron.statement.relation.Relation; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import java.io.IOException; import java.util.Iterator; import static org.animotron.graph.AnimoGraph.getORDER; import static org.neo4j.graphdb.Direction.OUTGOING; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovskyd@gmail.com">Evgeny Gazdovsky</a> * */ public class AnimoTraverser { public static AnimoTraverser _ = new AnimoTraverser(); protected Node node; protected AnimoTraverser() {} public void traverse(GraphHandler handler, PFlow pf, Relationship r) throws IOException { handler.startGraph(); build(handler, pf, r, 0, true); handler.endGraph(); } protected void build(GraphHandler handler, PFlow pf, Object o, int level, boolean isOne) throws IOException { if (o instanceof Relationship) { build(handler, pf, (Relationship) o, level, isOne); } else { String name = (String) o; Statement statement = Statements.name(name); String reference = (String) node.getProperty(name); handler.start(statement, reference, level, isOne); handler.end(statement, reference, level, isOne); } } protected void build(GraphHandler handler, PFlow pf, Relationship r, int level, boolean isOne) throws IOException { Statement statement = Statements.relationshipType(r); if (statement == null) return; handler.start(statement, r, level++, isOne); if (!(statement instanceof Relation)) { node = r.getEndNode(); It it = new It(node); int size = hasStatement(node, NAME._) ? 1 : 0; try { iterate(handler, pf, it, level, size); } finally { it.remove(); } } handler.end(statement, r, --level, isOne); } protected void iterate(GraphHandler handler, PFlow pf, It it, int level, int count) throws IOException { int n = 0; Object[] o = {null, null, null}; while (it.hasNext() && n < 3) o[n++] = it.next(); boolean isOne = n - count < 2; for (int i = 0; i < n; i++) build(handler, pf, o[i], level, isOne); while (it.hasNext()) build(handler, pf, it.next(), level, isOne); } protected boolean hasStatement(Node node, Statement s) { return node.hasProperty(s.name()) || node.hasRelationship(s.relationshipType(), OUTGOING); } protected class It implements Iterator <Object>, Iterable<Object> { private Iterator<String> p; private Iterator<Relationship> r; private IndexHits<Relationship> q; Object current = null; public It (Relationship r) { this(r.getEndNode()); } public It (Node n) { p = n.getPropertyKeys().iterator(); q = getORDER().query(n); r = q.iterator(); next(); } @Override public Iterator<Object> iterator() { return this; } @Override public boolean hasNext() { return current != null; } @Override public Object next() { Object next = current; current = step(); return next; } private Object step() { if (p.hasNext()) { String o = p.next(); if (Properties.VALUE.name().equals(o) || Properties.NAME.name().equals(o)|| Properties.BIN.name().equals(o)) { return step(); } else { return o; } } else if (r.hasNext()) { return r.next(); } else { return null; } } @Override public void remove() { q.close(); } } }
package StevenDimDoors.mod_pocketDim.items; import java.util.List; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import StevenDimDoors.mod_pocketDim.mod_pocketDim; import StevenDimDoors.mod_pocketDim.core.DimLink; import StevenDimDoors.mod_pocketDim.core.LinkTypes; import StevenDimDoors.mod_pocketDim.core.NewDimData; import StevenDimDoors.mod_pocketDim.core.PocketManager; import StevenDimDoors.mod_pocketDim.util.Point4D; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemRiftSignature extends Item { public ItemRiftSignature(int itemID) { super(itemID); this.setMaxStackSize(1); this.setMaxDamage(0); this.hasSubtypes = true; this.setCreativeTab(mod_pocketDim.dimDoorsCreativeTab); } @SideOnly(Side.CLIENT) @Override public boolean hasEffect(ItemStack stack) { //Make the item glow if it has one endpoint stored return (stack.getItemDamage() != 0); } public void registerIcons(IconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(mod_pocketDim.modid + ":" + this.getUnlocalizedName()); } @Override public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { //TODO- recognize doors and intelligently place rifts on them. // We must use onItemUseFirst() instead of onItemUse() because Minecraft checks // whether the user is in creative mode after calling onItemUse() and undoes any // damage we might set to indicate the rift sig has been activated. Otherwise, // we would need to rely on checking NBT tags for hasEffect() and that function // gets called constantly. Avoiding NBT lookups reduces our performance impact. // Return false on the client side to pass this request to the server if (world.isRemote) { return false; } //But... :( //We don't check for replaceable blocks. The user can deal with that. <_< y += 2; //Increase y by 2 to place the rift at head level if (!player.canPlayerEdit(x, y, z, side, stack)) { return true; } Point4DOrientation source = getSource(stack); int orientation = MathHelper.floor_double((double) ((player.rotationYaw + 180.0F) * 4.0F / 360.0F) - 0.5D) & 3; if (source != null) { //The link was used before and already has an endpoint stored. Create links connecting the two endpoints. NewDimData sourceDimension = PocketManager.getDimensionData(source.getDimension()); NewDimData destinationDimension = PocketManager.getDimensionData(world); DimLink link = sourceDimension.createLink(source.getX(), source.getY(), source.getZ(), LinkTypes.NORMAL,source.getOrientation()); DimLink reverse = destinationDimension.createLink(x, y, z, LinkTypes.NORMAL,orientation); destinationDimension.setDestination(link, x, y, z); sourceDimension.setDestination(reverse, source.getX(), source.getY(), source.getZ()); //Try placing a rift at the destination point if (!mod_pocketDim.blockRift.isBlockImmune(world, x, y, z)) { world.setBlock(x, y, z, mod_pocketDim.blockRift.blockID); } //Try placing a rift at the source point, but check if its world is loaded first World sourceWorld = DimensionManager.getWorld(sourceDimension.id()); if (sourceWorld != null && !mod_pocketDim.blockRift.isBlockImmune(sourceWorld, source.getX(), source.getY(), source.getZ())) { sourceWorld.setBlock(source.getX(), source.getY(), source.getZ(), mod_pocketDim.blockRift.blockID); } if (!player.capabilities.isCreativeMode) { stack.stackSize } clearSource(stack); player.sendChatToPlayer("Rift Created"); world.playSoundAtEntity(player,"mods.DimDoors.sfx.riftEnd", 0.6f, 1); } else { //TODO account for replaceable blocks like snow //The link signature has not been used. Store its current target as the first location. setSource(stack, x, y, z,orientation, PocketManager.getDimensionData(world)); player.sendChatToPlayer("Location Stored in Rift Signature"); world.playSoundAtEntity(player,"mods.DimDoors.sfx.riftStart", 0.6f, 1); } return true; } /** * allows items to add custom lines of information to the mouseover description */ @SuppressWarnings({ "unchecked", "rawtypes" }) @SideOnly(Side.CLIENT) public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) { Point4DOrientation source = getSource(par1ItemStack); if (source != null) { par3List.add("Leads to (" + source.getX() + ", " + source.getY() + ", " + source.getZ() + ") at dimension #" + source.getDimension()); } else { par3List.add("First click stores a location;"); par3List.add("second click creates a pair of"); par3List.add("rifts linking the two locations."); } } public static void setSource(ItemStack itemStack, int x, int y, int z, int orientation, NewDimData dimension) { NBTTagCompound tag = new NBTTagCompound(); tag.setInteger("linkX", x); tag.setInteger("linkY", y); tag.setInteger("linkZ", z); tag.setInteger("orientation", orientation); tag.setInteger("linkDimID", dimension.id()); itemStack.setTagCompound(tag); itemStack.setItemDamage(1); } public static void clearSource(ItemStack itemStack) { //Don't just set the tag to null since there may be other data there (e.g. for renamed items) NBTTagCompound tag = itemStack.getTagCompound(); tag.removeTag("linkX"); tag.removeTag("linkY"); tag.removeTag("linkZ"); tag.removeTag("orientation"); tag.removeTag("linkDimID"); itemStack.setItemDamage(0); } public static Point4DOrientation getSource(ItemStack itemStack) { if (itemStack.getItemDamage() != 0) { if (itemStack.hasTagCompound()) { NBTTagCompound tag = itemStack.getTagCompound(); Integer x = tag.getInteger("linkX"); Integer y = tag.getInteger("linkY"); Integer z = tag.getInteger("linkZ"); Integer orientation = tag.getInteger("orientation"); Integer dimID = tag.getInteger("linkDimID"); if (x != null && y != null && z != null && dimID != null) { return new Point4DOrientation(x, y, z,orientation, dimID); } } itemStack.setItemDamage(0); } return null; } static class Point4DOrientation { private Point4D point; private int orientation; Point4DOrientation(int x, int y, int z, int orientation, int dimID) { this.point= new Point4D(x,y,z,dimID); this.orientation=orientation; } int getX() { return point.getX(); } int getY() { return point.getY(); } int getZ() { return point.getZ(); } int getDimension() { return point.getDimension(); } int getOrientation() { return orientation; } } }
package org.apache.hadoop.hive.kafka; import kafka.api.PartitionOffsetRequestInfo; import kafka.common.ErrorMapping; import kafka.common.TopicAndPartition; import kafka.javaapi.OffsetRequest; import kafka.javaapi.OffsetResponse; import kafka.javaapi.PartitionMetadata; import kafka.javaapi.TopicMetadata; import kafka.javaapi.TopicMetadataRequest; import kafka.javaapi.consumer.SimpleConsumer; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.hive.kafka.camus.*; import org.apache.hadoop.hive.serde2.avro.AvroGenericRecordWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobContext; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.TaskAttemptContext; import org.apache.log4j.Logger; import java.io.IOException; import java.net.URI; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; /** * Input format for a Kafka pull job. */ public class KafkaInputFormat implements InputFormat<KafkaKey, AvroGenericRecordWritable> { public static final String KAFKA_BLACKLIST_TOPIC = "kafka.blacklist.topics"; public static final String KAFKA_WHITELIST_TOPIC = "kafka.whitelist.topics"; public static final String KAFKA_MOVE_TO_LAST_OFFSET_LIST = "kafka.move.to.last.offset.list"; public static final String KAFKA_CLIENT_BUFFER_SIZE = "kafka.client.buffer.size"; public static final String KAFKA_CLIENT_SO_TIMEOUT = "kafka.client.so.timeout"; public static final String KAFKA_MAX_PULL_HRS = "kafka.max.pull.hrs"; public static final String KAFKA_MAX_PULL_MINUTES_PER_TASK = "kafka.max.pull.minutes.per.task"; public static final String KAFKA_MAX_HISTORICAL_DAYS = "kafka.max.historical.days"; public static final String CAMUS_MESSAGE_DECODER_CLASS = "camus.message.decoder.class"; public static final String ETL_IGNORE_SCHEMA_ERRORS = "etl.ignore.schema.errors"; public static final String ETL_AUDIT_IGNORE_SERVICE_TOPIC_LIST = "etl.audit.ignore.service.topic.list"; public static final String CAMUS_WORK_ALLOCATOR_CLASS = "camus.work.allocator.class"; public static final String CAMUS_WORK_ALLOCATOR_DEFAULT = "com.linkedin.camus.workallocater.BaseAllocator"; private static Logger log = null; public KafkaInputFormat() { if (log == null) log = Logger.getLogger(getClass()); } public static void setLogger(Logger log){ KafkaInputFormat.log = log; } @Override public RecordReader<KafkaKey, AvroGenericRecordWritable> getRecordReader( InputSplit split, JobConf conf, Reporter reporter) throws IOException { return new KafkaRecordReader(split, conf, reporter); } public static String getKafkaBrokers(JobConf job) { return job.get(KafkaBackedTableProperties.KAFKA_URI); } /** * Gets the metadata from Kafka * * @param conf * @return */ public List<TopicMetadata> getKafkaMetadata(JobConf conf) { ArrayList<String> metaRequestTopics = new ArrayList<String>(); String brokerString = getKafkaBrokers(conf); if (brokerString.isEmpty()) throw new InvalidParameterException("kafka.brokers must contain at least one node"); List<String> brokers = Arrays.asList(brokerString.split("\\s*,\\s*")); Collections.shuffle(brokers); boolean fetchMetaDataSucceeded = false; int i = 0; List<TopicMetadata> topicMetadataList = null; Exception savedException = null; while (i < brokers.size() && !fetchMetaDataSucceeded) { log.info("Trying to connect to broker: " + brokers.get(i)); SimpleConsumer consumer = createConsumer(conf, brokers.get(i)); log.info(String.format("Fetching metadata from broker %s with client id %s for %d topic(s) %s", brokers.get(i), consumer.clientId(), metaRequestTopics.size(), metaRequestTopics)); try { topicMetadataList = consumer.send(new TopicMetadataRequest(metaRequestTopics)).topicsMetadata(); fetchMetaDataSucceeded = true; } catch (Exception e) { savedException = e; log.warn(String.format("Fetching topic metadata with client id %s for topics [%s] from broker [%s] failed", consumer.clientId(), metaRequestTopics, brokers.get(i)), e); } finally { consumer.close(); i++; } } if (!fetchMetaDataSucceeded) { throw new RuntimeException("Failed to obtain metadata!", savedException); } return topicMetadataList; } private SimpleConsumer createConsumer(JobConf conf, String broker) { if (!broker.matches(".+:\\d+")) throw new InvalidParameterException("The kakfa broker " + broker + " must follow address:port pattern"); String[] hostPort = broker.split(":"); //TODO: get from conf SimpleConsumer consumer = new SimpleConsumer( hostPort[0], Integer.valueOf(hostPort[1]), 30000, 1024 * 1024, "hive_kafka_client"); return consumer; } /** * Gets the latest offsets and create the requests as needed * * @param conf * @param offsetRequestInfo * @return */ public ArrayList<CamusRequest> fetchLatestOffsetAndCreateKafkaRequests( JobConf conf, HashMap<LeaderInfo, ArrayList<TopicAndPartition>> offsetRequestInfo) { ArrayList<CamusRequest> finalRequests = new ArrayList<CamusRequest>(); for (LeaderInfo leader : offsetRequestInfo.keySet()) { SimpleConsumer consumer = new SimpleConsumer(leader.getUri() .getHost(), leader.getUri().getPort(), 30000, 1024 * 1024, "hive_kafka_client"); // Latest Offset PartitionOffsetRequestInfo partitionLatestOffsetRequestInfo = new PartitionOffsetRequestInfo( kafka.api.OffsetRequest.LatestTime(), 1); // Earliest Offset PartitionOffsetRequestInfo partitionEarliestOffsetRequestInfo = new PartitionOffsetRequestInfo( kafka.api.OffsetRequest.EarliestTime(), 1); Map<TopicAndPartition, PartitionOffsetRequestInfo> latestOffsetInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>(); Map<TopicAndPartition, PartitionOffsetRequestInfo> earliestOffsetInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>(); ArrayList<TopicAndPartition> topicAndPartitions = offsetRequestInfo .get(leader); for (TopicAndPartition topicAndPartition : topicAndPartitions) { latestOffsetInfo.put(topicAndPartition, partitionLatestOffsetRequestInfo); earliestOffsetInfo.put(topicAndPartition, partitionEarliestOffsetRequestInfo); } OffsetResponse latestOffsetResponse = consumer .getOffsetsBefore(new OffsetRequest(latestOffsetInfo, kafka.api.OffsetRequest.CurrentVersion(), "hive_kafka_client")); OffsetResponse earliestOffsetResponse = consumer .getOffsetsBefore(new OffsetRequest(earliestOffsetInfo, kafka.api.OffsetRequest.CurrentVersion(), "hive_kafka_client")); consumer.close(); for (TopicAndPartition topicAndPartition : topicAndPartitions) { long latestOffset = latestOffsetResponse.offsets( topicAndPartition.topic(), topicAndPartition.partition())[0]; long earliestOffset = earliestOffsetResponse.offsets( topicAndPartition.topic(), topicAndPartition.partition())[0]; //TODO: factor out kafka specific request functionality CamusRequest etlRequest = new KafkaRequest(conf, topicAndPartition.topic(), Integer.toString(leader .getLeaderId()), topicAndPartition.partition(), leader.getUri()); etlRequest.setLatestOffset(latestOffset); etlRequest.setEarliestOffset(earliestOffset); finalRequests.add(etlRequest); } } return finalRequests; } public String createTopicRegEx(HashSet<String> topicsSet) { String regex = ""; StringBuilder stringbuilder = new StringBuilder(); for (String whiteList : topicsSet) { stringbuilder.append(whiteList); stringbuilder.append("|"); } regex = "(" + stringbuilder.substring(0, stringbuilder.length() - 1) + ")"; Pattern.compile(regex); return regex; } public List<TopicMetadata> filterWhitelistTopics( List<TopicMetadata> topicMetadataList, HashSet<String> whiteListTopics) { ArrayList<TopicMetadata> filteredTopics = new ArrayList<TopicMetadata>(); String regex = createTopicRegEx(whiteListTopics); for (TopicMetadata topicMetadata : topicMetadataList) { if (Pattern.matches(regex, topicMetadata.topic())) { filteredTopics.add(topicMetadata); } else { log.info("Discarding topic : " + topicMetadata.topic()); } } return filteredTopics; } @Override public InputSplit[] getSplits(JobConf conf, int numSplits) throws IOException { ArrayList<CamusRequest> finalRequests; HashMap<LeaderInfo, ArrayList<TopicAndPartition>> offsetRequestInfo = new HashMap<LeaderInfo, ArrayList<TopicAndPartition>>(); try { // Get Metadata for all topics List<TopicMetadata> topicMetadataList = getKafkaMetadata(conf); // Filter any white list topics HashSet<String> whiteListTopics = new HashSet<String>( Arrays.asList(getKafkaWhitelistTopic(conf))); if (!whiteListTopics.isEmpty()) { topicMetadataList = filterWhitelistTopics(topicMetadataList, whiteListTopics); } // Filter all blacklist topics HashSet<String> blackListTopics = new HashSet<String>( Arrays.asList(getKafkaBlacklistTopic(conf))); String regex = ""; if (!blackListTopics.isEmpty()) { regex = createTopicRegEx(blackListTopics); } for (TopicMetadata topicMetadata : topicMetadataList) { if (Pattern.matches(regex, topicMetadata.topic())) { log.info("Discarding topic (blacklisted): " + topicMetadata.topic()); } else if (!createMessageDecoder(conf, topicMetadata.topic())) { log.info("Discarding topic (Decoder generation failed) : " + topicMetadata.topic()); } else if (topicMetadata.errorCode() != ErrorMapping.NoError()) { log.info("Skipping the creation of ETL request for Whole Topic : " + topicMetadata.topic() + " Exception : " + ErrorMapping .exceptionFor(topicMetadata .errorCode())); } else { for (PartitionMetadata partitionMetadata : topicMetadata .partitionsMetadata()) { // We only care about LeaderNotAvailableCode error on partitionMetadata level // Error codes such as ReplicaNotAvailableCode should not stop us. if (partitionMetadata.errorCode() == ErrorMapping.LeaderNotAvailableCode()) { log.info("Skipping the creation of ETL request for Topic : " + topicMetadata.topic() + " and Partition : " + partitionMetadata.partitionId() + " Exception : " + ErrorMapping .exceptionFor(partitionMetadata .errorCode())); } else { if (partitionMetadata.errorCode() != ErrorMapping.NoError()) { log.warn("Receiving non-fatal error code, Continuing the creation of ETL request for Topic : " + topicMetadata.topic() + " and Partition : " + partitionMetadata.partitionId() + " Exception : " + ErrorMapping .exceptionFor(partitionMetadata .errorCode())); } LeaderInfo leader = new LeaderInfo(new URI("tcp: + partitionMetadata.leader() .getConnectionString()), partitionMetadata.leader().id()); if (offsetRequestInfo.containsKey(leader)) { ArrayList<TopicAndPartition> topicAndPartitions = offsetRequestInfo .get(leader); topicAndPartitions.add(new TopicAndPartition( topicMetadata.topic(), partitionMetadata.partitionId())); offsetRequestInfo.put(leader, topicAndPartitions); } else { ArrayList<TopicAndPartition> topicAndPartitions = new ArrayList<TopicAndPartition>(); topicAndPartitions.add(new TopicAndPartition( topicMetadata.topic(), partitionMetadata.partitionId())); offsetRequestInfo.put(leader, topicAndPartitions); } } } } } } catch (Exception e) { log.error( "Unable to pull requests from Kafka brokers. Exiting the program", e); return null; } // Get the latest offsets and generate the KafkaRequests finalRequests = fetchLatestOffsetAndCreateKafkaRequests(conf, offsetRequestInfo); Collections.sort(finalRequests, new Comparator<CamusRequest>() { public int compare(CamusRequest r1, CamusRequest r2) { return r1.getTopic().compareTo(r2.getTopic()); } }); log.info("The requests from kafka metadata are: \n" + finalRequests); //writeRequests(finalRequests, context); Map<CamusRequest, KafkaKey> offsetKeys = getPreviousOffsets( FileInputFormat.getInputPaths(conf),conf); Set<String> moveLatest = getMoveToLatestTopicsSet(conf); for (CamusRequest request : finalRequests) { if (moveLatest.contains(request.getTopic()) || moveLatest.contains("all")) { log.info("Moving to latest for topic: " + request.getTopic()); //TODO: factor out kafka specific request functionality KafkaKey oldKey = offsetKeys.get(request); KafkaKey newKey = new KafkaKey(request.getTopic(), ((KafkaRequest)request).getLeaderId(), request.getPartition(), 0, request .getLastOffset()); if (oldKey != null) newKey.setMessageSize(oldKey.getMessageSize()); offsetKeys.put(request, newKey); } KafkaKey key = offsetKeys.get(request); if (key != null) { request.setOffset(key.getOffset()); request.setAvgMsgSize(key.getMessageSize()); } if (request.getEarliestOffset() > request.getOffset() || request.getOffset() > request.getLastOffset()) { if(request.getEarliestOffset() > request.getOffset()) { log.error("The earliest offset was found to be more than the current offset: " + request); log.error("Moving to the earliest offset available"); } else { log.error("The current offset was found to be more than the latest offset: " + request); log.error("Moving to the earliest offset available"); } request.setOffset(request.getEarliestOffset()); offsetKeys.put( request, //TODO: factor out kafka specific request functionality new KafkaKey(request.getTopic(), ((KafkaRequest)request).getLeaderId(), request.getPartition(), 0, request .getOffset())); } log.info(request); } //writePrevious(offsetKeys.values(), context); WorkAllocator allocator = getWorkAllocator(conf); Properties props = new Properties(); props.putAll(conf.getValByRegex(".*")); allocator.init(props); return allocator.allocateWork(finalRequests, conf); } private Set<String> getMoveToLatestTopicsSet(JobConf conf) { Set<String> topics = new HashSet<String>(); String[] arr = getMoveToLatestTopics(conf); if (arr != null) { for (String topic : arr) { topics.add(topic); } } return topics; } private boolean createMessageDecoder(JobConf conf, String topic) { try { MessageDecoderFactory.createMessageDecoder(conf, topic); return true; } catch (Exception e) { log.error("failed to create decoder", e); return false; } } /* private void writePrevious(Collection<KafkaKey> missedKeys, JobContext context) throws IOException { FileSystem fs = FileSystem.get(context.getConfiguration()); Path output = FileOutputFormat.getOutputPath(context); if (fs.exists(output)) { fs.mkdirs(output); } output = new Path(output, KafkaMultiOutputFormat.OFFSET_PREFIX + "-previous"); SequenceFile.Writer writer = SequenceFile.createWriter(fs, context.getConfiguration(), output, KafkaKey.class, NullWritable.class); for (KafkaKey key : missedKeys) { writer.append(key, NullWritable.get()); } writer.close(); } */ /* private void writeRequests(List<CamusRequest> requests, JobContext context) throws IOException { FileSystem fs = FileSystem.get(context.getConfiguration()); Path output = FileOutputFormat.getOutputPath(context); if (fs.exists(output)) { fs.mkdirs(output); } output = new Path(output, KafkaMultiOutputFormat.REQUESTS_FILE); SequenceFile.Writer writer = SequenceFile.createWriter(fs, context.getConfiguration(), output, KafkaRequest.class, NullWritable.class); for (CamusRequest r : requests) { //TODO: factor out kafka specific request functionality writer.append((KafkaRequest) r, NullWritable.get()); } writer.close(); } */ private Map<CamusRequest, KafkaKey> getPreviousOffsets(Path[] inputs, JobConf conf) throws IOException { Map<CamusRequest, KafkaKey> offsetKeysMap = new HashMap<CamusRequest, KafkaKey>(); for (Path input : inputs) { FileSystem fs = input.getFileSystem(conf); for (FileStatus f : fs.listStatus(input, new OffsetFileFilter())) { log.info("previous offset file:" + f.getPath().toString()); SequenceFile.Reader reader = new SequenceFile.Reader(fs, f.getPath(), conf); KafkaKey key = new KafkaKey(); while (reader.next(key, NullWritable.get())) { //TODO: factor out kafka specific request functionality CamusRequest request = new KafkaRequest(conf, key.getTopic(), key.getLeaderId(), key.getPartition()); if (offsetKeysMap.containsKey(request)) { KafkaKey oldKey = offsetKeysMap.get(request); if (oldKey.getOffset() < key.getOffset()) { offsetKeysMap.put(request, key); } } else { offsetKeysMap.put(request, key); } key = new KafkaKey(); } reader.close(); } } return offsetKeysMap; } public static void setWorkAllocator(JobContext job, Class<WorkAllocator> val) { job.getConfiguration().setClass(CAMUS_WORK_ALLOCATOR_CLASS, val, WorkAllocator.class); } public static WorkAllocator getWorkAllocator(JobConf job) { try { return (WorkAllocator) job.getClass(BaseAllocator.class.getName(), BaseAllocator.class).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public static void setMoveToLatestTopics(JobContext job, String val) { job.getConfiguration().set(KAFKA_MOVE_TO_LAST_OFFSET_LIST, val); } public static String[] getMoveToLatestTopics(JobConf job) { return job.getStrings(KAFKA_MOVE_TO_LAST_OFFSET_LIST); } public static void setKafkaClientBufferSize(JobContext job, int val) { job.getConfiguration().setInt(KAFKA_CLIENT_BUFFER_SIZE, val); } public static int getKafkaClientBufferSize(JobContext job) { return job.getConfiguration().getInt(KAFKA_CLIENT_BUFFER_SIZE, 2 * 1024 * 1024); } public static void setKafkaClientTimeout(JobContext job, int val) { job.getConfiguration().setInt(KAFKA_CLIENT_SO_TIMEOUT, val); } public static int getKafkaClientTimeout(JobContext job) { return job.getConfiguration().getInt(KAFKA_CLIENT_SO_TIMEOUT, 60000); } public static void setKafkaMaxPullHrs(JobContext job, int val) { job.getConfiguration().setInt(KAFKA_MAX_PULL_HRS, val); } public static int getKafkaMaxPullHrs(JobContext job) { return job.getConfiguration().getInt(KAFKA_MAX_PULL_HRS, -1); } public static void setKafkaMaxPullMinutesPerTask(JobContext job, int val) { job.getConfiguration().setInt(KAFKA_MAX_PULL_MINUTES_PER_TASK, val); } public static int getKafkaMaxPullMinutesPerTask(JobContext job) { return job.getConfiguration().getInt(KAFKA_MAX_PULL_MINUTES_PER_TASK, -1); } public static void setKafkaMaxHistoricalDays(JobContext job, int val) { job.getConfiguration().setInt(KAFKA_MAX_HISTORICAL_DAYS, val); } public static int getKafkaMaxHistoricalDays(JobContext job) { return job.getConfiguration().getInt(KAFKA_MAX_HISTORICAL_DAYS, -1); } public static void setKafkaBlacklistTopic(JobContext job, String val) { job.getConfiguration().set(KAFKA_BLACKLIST_TOPIC, val); } public static String[] getKafkaBlacklistTopic(JobConf job) { if (job.get(KAFKA_BLACKLIST_TOPIC) != null && !(job.get(KAFKA_BLACKLIST_TOPIC).isEmpty())) { return job.getStrings(KAFKA_BLACKLIST_TOPIC); } else { return new String[] {}; } } public static void setKafkaWhitelistTopic(JobContext job, String val) { job.getConfiguration().set(KAFKA_WHITELIST_TOPIC, val); } public static String[] getKafkaWhitelistTopic(JobConf job) { if (job.get(KAFKA_WHITELIST_TOPIC) != null && !job.get(KAFKA_WHITELIST_TOPIC).isEmpty()) { return job.getStrings(KAFKA_WHITELIST_TOPIC); } else { return new String[] {}; } } public static void setKafkaIgnoreSchemaErrors(JobContext job, boolean val) { job.getConfiguration().setBoolean(ETL_IGNORE_SCHEMA_ERRORS, val); } public static boolean getKafkaIgnoreSchemaErrors(JobContext job) { return job.getConfiguration().getBoolean(ETL_IGNORE_SCHEMA_ERRORS, false); } public static void setKafkaAuditIgnoreServiceTopicList(JobContext job, String topics) { job.getConfiguration().set(ETL_AUDIT_IGNORE_SERVICE_TOPIC_LIST, topics); } public static void setMessageDecoderClass(JobContext job, Class<MessageDecoder> cls) { job.getConfiguration().setClass(CAMUS_MESSAGE_DECODER_CLASS, cls, MessageDecoder.class); } public static Class<MessageDecoder> getMessageDecoderClass(JobContext job) { return (Class<MessageDecoder>) job.getConfiguration().getClass( CAMUS_MESSAGE_DECODER_CLASS, KafkaAvroMessageDecoder.class); } private class OffsetFileFilter implements PathFilter { @Override public boolean accept(Path arg0) { return arg0.getName() .startsWith("kafka_offset_"); } } }
package org.biocreative.bioc.io.standard; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.DTD; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.commons.lang3.Validate; import org.biocreative.bioc.BioCAnnotation; import org.biocreative.bioc.BioCCollection; import org.biocreative.bioc.BioCDocument; import org.biocreative.bioc.BioCLocation; import org.biocreative.bioc.BioCNode; import org.biocreative.bioc.BioCPassage; import org.biocreative.bioc.BioCRelation; import org.biocreative.bioc.BioCSentence; /** * can only read collection DTD or sentence DTD */ class BioCReader2 implements Closeable { static enum Level { COLLECTION_LEVEL, DOCUMENT_LEVEL, PASSAGE_LEVEL, SENTENCE_LEVEL } BioCCollection.Builder collectionBuilder; BioCDocument.Builder documentBuilder; BioCPassage.Builder passageBuilder; BioCSentence.Builder sentenceBuilder; XMLEventReader reader; String dtd; private int state; Level level; public BioCReader2(Reader reader, Level level) throws FactoryConfigurationError, XMLStreamException { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); factory.setProperty(XMLInputFactory.IS_COALESCING, false); factory.setProperty(XMLInputFactory.IS_VALIDATING, false); factory.setProperty(XMLInputFactory.SUPPORT_DTD, true); this.reader = factory.createXMLEventReader(reader); this.level = level; state = 0; } protected String getDtd() { return dtd; } @Override public void close() throws IOException { try { reader.close(); } catch (XMLStreamException e) { throw new IOException(e.getMessage(), e); } } protected Object read() throws XMLStreamException { String localName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); switch (state) { case 0: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("collection")) { collectionBuilder = BioCCollection.newBuilder(); state = 1; } } if (event.getEventType() == XMLStreamConstants.DTD) { DTD dtd = (DTD) event; this.dtd = dtd.getDocumentTypeDeclaration(); } break; case 1: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("source")) { collectionBuilder.setSource(getText()); } else if (localName.equals("date")) { collectionBuilder.setDate(getText()); } else if (localName.equals("key")) { collectionBuilder.setKey(getText()); } else if (localName.equals("infon")) { collectionBuilder.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("document")) { // read document documentBuilder = BioCDocument.newBuilder(); state = 2; } else { ; } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("collection")) { sentenceBuilder = null; passageBuilder = null; documentBuilder = null; state = 0; } break; } break; case 2: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("id")) { documentBuilder.setID(getText()); } else if (localName.equals("infon")) { documentBuilder.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("passage")) { // read passage passageBuilder = BioCPassage.newBuilder(); state = 3; } else if (localName.equals("relation")) { // read relation documentBuilder.addRelation(readRelation(startElement)); } else { ; } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("document")) { state = 1; if (level == Level.DOCUMENT_LEVEL) { return documentBuilder.build(); } else if (documentBuilder != null) { collectionBuilder.addDocument(documentBuilder.build()); } } break; } break; case 3: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("offset")) { passageBuilder.setOffset(Integer.parseInt(getText())); } else if (localName.equals("text")) { passageBuilder.setText(getText()); } else if (localName.equals("infon")) { passageBuilder.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("annotation")) { passageBuilder.addAnnotation(readAnnotation(startElement)); } else if (localName.equals("relation")) { passageBuilder.addRelation(readRelation(startElement)); } else if (localName.equals("sentence")) { // read sentence sentenceBuilder = BioCSentence.newBuilder(); state = 4; } else { ; } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("passage")) { state = 2; if (level == Level.PASSAGE_LEVEL) { return passageBuilder.build(); } else if (passageBuilder != null) { documentBuilder.addPassage(passageBuilder.build()); } } break; } break; case 4: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("offset")) { sentenceBuilder.setOffset(Integer.parseInt(getText())); } else if (localName.equals("text")) { sentenceBuilder.setText(getText()); } else if (localName.equals("infon")) { sentenceBuilder.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("annotation")) { sentenceBuilder.addAnnotation(readAnnotation(startElement)); } else if (localName.equals("relation")) { sentenceBuilder.addRelation(readRelation(startElement)); } else { ; } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("sentence")) { state = 3; if (level == Level.SENTENCE_LEVEL) { return sentenceBuilder.build(); } else if (sentenceBuilder != null) { passageBuilder.addSentence(sentenceBuilder.build()); } } break; } } } return collectionBuilder.build(); } private String getText() throws XMLStreamException { return reader.nextEvent().asCharacters().getData(); } private BioCAnnotation readAnnotation(StartElement annotationEvent) throws XMLStreamException { BioCAnnotation.Builder annBuilder = BioCAnnotation.newBuilder(); annBuilder.setID(getAttribute(annotationEvent, "id")); String localName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("text")) { annBuilder.setText(getText()); } else if (localName.equals("infon")) { annBuilder.putInfon( startElement.getAttributeByName(new QName("key")).getValue(), getText()); } else if (localName.equals("location")) { annBuilder.addLocation(BioCLocation .newBuilder() .setOffset( Integer.parseInt(getAttribute(startElement, "offset"))) .setLength( Integer.parseInt(getAttribute(startElement, "length"))) .build()); } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("annotation")) { return annBuilder.build(); } } } Validate.isTrue(false, "should not reach here"); return null; } private BioCRelation readRelation(StartElement relationEvent) throws XMLStreamException { BioCRelation.Builder relBuilder = BioCRelation.newBuilder(); relBuilder.setID(getAttribute(relationEvent, "id")); String localName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("infon")) { relBuilder.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("node")) { BioCNode node = BioCNode .newBuilder() .setRefid(getAttribute(startElement, "refid")) .setRole(getAttribute(startElement, "role")) .build(); relBuilder.addNode(node); } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("relation")) { return relBuilder.build(); } } } Validate.isTrue(false, "should not reach here"); return null; } private String getAttribute(StartElement startElement, String key) { return startElement.getAttributeByName(new QName(key)).getValue(); } }
package org.concord.datagraph.analysis; import java.awt.Component; import org.concord.data.state.OTDataStore; import org.concord.datagraph.analysis.rubric.GraphRubric; import org.concord.datagraph.analysis.rubric.ResultSet; import org.concord.framework.otrunk.OTObjectList; public interface GraphAnalyzer { public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException; public GraphRubric buildRubric(OTObjectList rubric); public ResultSet compareGraphs(GraphRubric expected, Graph received); public String getHtmlReasons(ResultSet results); public void displayHtmlReasonsPopup(Component parent, ResultSet results); }
package org.dasein.cloud.network; import org.dasein.cloud.CloudException; import org.dasein.cloud.CloudProvider; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.compute.ComputeServices; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VirtualMachineSupport; import org.dasein.cloud.identity.ServiceAction; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public abstract class AbstractVLANSupport implements VLANSupport { private CloudProvider provider; public AbstractVLANSupport(@Nonnull CloudProvider provider) { this.provider = provider; } @Override public void addRouteToAddress(@Nonnull String toRoutingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String address) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void addRouteToGateway(@Nonnull String toRoutingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String gatewayId) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void addRouteToNetworkInterface(@Nonnull String toRoutingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String nicId) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void addRouteToVirtualMachine(@Nonnull String toRoutingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String vmId) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public boolean allowsNewNetworkInterfaceCreation() throws CloudException, InternalException { return false; } @Override public boolean allowsNewVlanCreation() throws CloudException, InternalException { return false; } @Override public boolean allowsNewSubnetCreation() throws CloudException, InternalException { return false; } @Override public void assignRoutingTableToSubnet(@Nonnull String subnetId, @Nonnull String routingTableId) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void assignRoutingTableToVlan(@Nonnull String vlanId, @Nonnull String routingTableId) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void attachNetworkInterface(@Nonnull String nicId, @Nonnull String vmId, int index) throws CloudException, InternalException { throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName()); } @Override public String createInternetGateway(@Nonnull String forVlanId) throws CloudException, InternalException { throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName()); } @Override public @Nonnull String createRoutingTable(@Nonnull String forVlanId, @Nonnull String name, @Nonnull String description) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public @Nonnull NetworkInterface createNetworkInterface(@Nonnull NICCreateOptions options) throws CloudException, InternalException { throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName()); } @Override @Deprecated public @Nonnull Subnet createSubnet(@Nonnull String cidr, @Nonnull String inProviderVlanId, @Nonnull String name, @Nonnull String description) throws CloudException, InternalException { return createSubnet(SubnetCreateOptions.getInstance(inProviderVlanId, cidr, name, description)); } @Override public @Nonnull Subnet createSubnet(@Nonnull SubnetCreateOptions options) throws CloudException, InternalException { throw new OperationNotSupportedException("Subnets are not currently implemented for " + getProvider().getCloudName()); } @Override public @Nonnull VLAN createVlan(@Nonnull String cidr, @Nonnull String name, @Nonnull String description, @Nonnull String domainName, @Nonnull String[] dnsServers, @Nonnull String[] ntpServers) throws CloudException, InternalException { throw new OperationNotSupportedException("VLANs are not currently implemented for " + getProvider().getCloudName()); } @Override public void detachNetworkInterface(@Nonnull String nicId) throws CloudException, InternalException { throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName()); } @Override public int getMaxNetworkInterfaceCount() throws CloudException, InternalException { return 0; } @Override public int getMaxVlanCount() throws CloudException, InternalException { return 0; } @Override public NetworkInterface getNetworkInterface(@Nonnull String nicId) throws CloudException, InternalException { for( NetworkInterface nic : listNetworkInterfaces() ) { if( nicId.equals(nic.getProviderNetworkInterfaceId()) ) { return nic; } } return null; } @Override public RoutingTable getRoutingTableForSubnet(@Nonnull String subnetId) throws CloudException, InternalException { return null; } @Override public @Nonnull Requirement getRoutingTableSupport() throws CloudException, InternalException { return Requirement.NONE; } @Override public RoutingTable getRoutingTableForVlan(@Nonnull String vlanId) throws CloudException, InternalException { return null; } @Override public Subnet getSubnet(@Nonnull String subnetId) throws CloudException, InternalException { for( VLAN vlan : listVlans() ) { for( Subnet subnet : listSubnets(vlan.getProviderVlanId()) ) { if( subnet.getProviderSubnetId().equals(subnetId) ) { return subnet; } } } return null; } @Override public @Nonnull Requirement getSubnetSupport() throws CloudException, InternalException { return Requirement.NONE; } @Override public VLAN getVlan(@Nonnull String vlanId) throws CloudException, InternalException { for( VLAN vlan : listVlans() ) { if( vlan.getProviderVlanId().equals(vlanId) ) { return vlan; } } return null; } /** * @return the current operational context for this support object * @throws CloudException */ protected @Nonnull ProviderContext getContext() throws CloudException { ProviderContext ctx = getProvider().getContext(); if( ctx == null ) { throw new CloudException("No context was set for this request"); } return ctx; } /** * @return the provider object governing this support object */ protected final @Nonnull CloudProvider getProvider() { return provider; } @Override public @Nonnull Requirement identifySubnetDCRequirement() { return Requirement.NONE; } @Override public boolean isNetworkInterfaceSupportEnabled() throws CloudException, InternalException { return false; } @Override public boolean isSubnetDataCenterConstrained() throws CloudException, InternalException { return false; } @Override public boolean isVlanDataCenterConstrained() throws CloudException, InternalException { return false; } @Override public @Nonnull Collection<String> listFirewallIdsForNIC(@Nonnull String nicId) throws CloudException, InternalException { return Collections.emptyList(); } @Override public @Nonnull Iterable<ResourceStatus> listNetworkInterfaceStatus() throws CloudException, InternalException { ArrayList<ResourceStatus> status = new ArrayList<ResourceStatus>(); for( NetworkInterface nic : listNetworkInterfaces() ) { status.add(new ResourceStatus(nic.getProviderNetworkInterfaceId(), nic.getCurrentState())); } return status; } @Override public @Nonnull Iterable<NetworkInterface> listNetworkInterfaces() throws CloudException, InternalException { return Collections.emptyList(); } @Override public @Nonnull Iterable<NetworkInterface> listNetworkInterfacesForVM(@Nonnull String forVmId) throws CloudException, InternalException { ArrayList<NetworkInterface> nics = new ArrayList<NetworkInterface>(); for( NetworkInterface nic : listNetworkInterfaces() ) { if( forVmId.equals(nic.getProviderVirtualMachineId()) ) { nics.add(nic); } } return nics; } @Override public @Nonnull Iterable<NetworkInterface> listNetworkInterfacesInSubnet(@Nonnull String subnetId) throws CloudException, InternalException { ArrayList<NetworkInterface> nics = new ArrayList<NetworkInterface>(); for( NetworkInterface nic : listNetworkInterfaces() ) { if( subnetId.equals(nic.getProviderSubnetId()) ) { nics.add(nic); } } return nics; } @Override public @Nonnull Iterable<NetworkInterface> listNetworkInterfacesInVLAN(@Nonnull String vlanId) throws CloudException, InternalException { ArrayList<NetworkInterface> nics = new ArrayList<NetworkInterface>(); for( NetworkInterface nic : listNetworkInterfaces() ) { if( vlanId.equals(nic.getProviderVlanId()) ) { nics.add(nic); } } return nics; } @Override public @Nonnull Iterable<Networkable> listResources(@Nonnull String inVlanId) throws CloudException, InternalException { ArrayList<Networkable> resources = new ArrayList<Networkable>(); NetworkServices network = provider.getNetworkServices(); if( network != null ) { FirewallSupport fwSupport = network.getFirewallSupport(); if( fwSupport != null ) { for( Firewall fw : fwSupport.list() ) { if( inVlanId.equals(fw.getProviderVlanId()) ) { resources.add(fw); } } } IpAddressSupport ipSupport = network.getIpAddressSupport(); if( ipSupport != null ) { for( IPVersion version : ipSupport.listSupportedIPVersions() ) { for( IpAddress addr : ipSupport.listIpPool(version, false) ) { if( inVlanId.equals(addr.getProviderVlanId()) ) { resources.add(addr); } } } } for( RoutingTable table : listRoutingTables(inVlanId) ) { resources.add(table); } ComputeServices compute = provider.getComputeServices(); VirtualMachineSupport vmSupport = compute == null ? null : compute.getVirtualMachineSupport(); Iterable<VirtualMachine> vms; if( vmSupport == null ) { vms = Collections.emptyList(); } else { vms = vmSupport.listVirtualMachines(); } for( Subnet subnet : listSubnets(inVlanId) ) { resources.add(subnet); for( VirtualMachine vm : vms ) { if( subnet.getProviderSubnetId().equals(vm.getProviderVlanId()) ) { resources.add(vm); } } } } return resources; } @Override public @Nonnull Iterable<RoutingTable> listRoutingTables(@Nonnull String inVlanId) throws CloudException, InternalException { return Collections.emptyList(); } @Override public @Nonnull Iterable<Subnet> listSubnets(@Nonnull String inVlanId) throws CloudException, InternalException { return Collections.emptyList(); } @Override public @Nonnull Iterable<IPVersion> listSupportedIPVersions() throws CloudException, InternalException { return Collections.singletonList(IPVersion.IPV4); } @Override public @Nonnull Iterable<ResourceStatus> listVlanStatus() throws CloudException, InternalException { ArrayList<ResourceStatus> status = new ArrayList<ResourceStatus>(); for( VLAN vlan : listVlans() ) { status.add(new ResourceStatus(vlan.getProviderVlanId(), vlan.getCurrentState())); } return status; } @Override public @Nonnull Iterable<VLAN> listVlans() throws CloudException, InternalException { return Collections.emptyList(); } @Override public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) { return new String[0]; } @Override public void removeInternetGateway(@Nonnull String forVlanId) throws CloudException, InternalException { throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName()); } @Override public void removeNetworkInterface(@Nonnull String nicId) throws CloudException, InternalException { throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName()); } @Override public void removeRoute(@Nonnull String inRoutingTableId, @Nonnull String destinationCidr) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void removeRoutingTable(@Nonnull String routingTableId) throws CloudException, InternalException { throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName()); } @Override public void removeSubnet(String providerSubnetId) throws CloudException, InternalException { throw new OperationNotSupportedException("Subnets are not currently implemented for " + getProvider().getCloudName()); } @Override public void removeVlan(String vlanId) throws CloudException, InternalException { throw new OperationNotSupportedException("VLANs are not currently implemented for " + getProvider().getCloudName()); } @Override public boolean supportsInternetGatewayCreation() throws CloudException, InternalException { return false; } @Override public boolean supportsRawAddressRouting() throws CloudException, InternalException { return false; } }
package edu.wustl.cab2b.client.ui.main; import java.awt.Dimension; import java.lang.reflect.Constructor; import java.util.ArrayList; import edu.common.dynamicextensions.domain.BooleanAttributeTypeInformation; import edu.common.dynamicextensions.domain.ByteArrayAttributeTypeInformation; import edu.common.dynamicextensions.domain.DateAttributeTypeInformation; import edu.common.dynamicextensions.domain.DoubleAttributeTypeInformation; import edu.common.dynamicextensions.domain.FloatAttributeTypeInformation; import edu.common.dynamicextensions.domain.IntegerAttributeTypeInformation; import edu.common.dynamicextensions.domain.LongAttributeTypeInformation; import edu.common.dynamicextensions.domain.NumericAttributeTypeInformation; import edu.common.dynamicextensions.domain.ShortAttributeTypeInformation; import edu.common.dynamicextensions.domain.StringAttributeTypeInformation; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface; import edu.wustl.cab2b.common.errorcodes.ErrorCodeConstants; import edu.wustl.cab2b.common.exception.CheckedException; /** * This class is used for creating UI panel that shows attribute name, data-type * conditions and components for entering/showing the values. * * @author Kaushal Kumar * @version 1.0 */ public class SwingUIManager { /** * This method returns a panel object that shows attribute name, data-type * conditions and components for entering/showing the values. * * @param parseFile * @param entity * @return panel object */ public static Object generateUIPanel(ParseXMLFile parseFile, AttributeInterface attributeEntity, boolean showConditions, Dimension maxLabelDimension) throws CheckedException { Object[] object = new Object[4]; String className = null; AttributeTypeInformationInterface attributeTypeInformation = attributeEntity.getAttributeTypeInformation(); String dataTypeString = getDataType(attributeTypeInformation); // Check if attribute has value domain (i.e it is enum) if (true == edu.wustl.cab2b.common.util.Utility.isEnumerated(attributeEntity)) { object[0] = parseFile.getEnumConditionList(dataTypeString); className = parseFile.getEnumClassName(dataTypeString); } else { // If an entity is of non-enumerated type object[0] = parseFile.getNonEnumConditionList(dataTypeString); className = parseFile.getNonEnumClassName(dataTypeString); } object[1] = attributeEntity; object[2] = new Boolean(showConditions); object[3] = maxLabelDimension; Object uiObject = null; try { Class[] arr = { ArrayList.class, AttributeInterface.class, Boolean.class, Dimension.class }; Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getDeclaredConstructor(arr); uiObject = constructor.newInstance(object); } catch (Exception e) { throw new CheckedException(e.getMessage(), e, ErrorCodeConstants.RF_0001); } return uiObject; } public static Object generateParameterizedUIPanel(ParseXMLFile parseFile, AttributeInterface attributeEntity, boolean showConditions, Dimension maxLabelDimension) throws CheckedException { Object[] object = new Object[5]; String className = null; AttributeTypeInformationInterface attributeTypeInformation = attributeEntity.getAttributeTypeInformation(); String dataTypeString = getDataType(attributeTypeInformation); // Check if attribute has value domain (i.e it is enum) if (true == edu.wustl.cab2b.common.util.Utility.isEnumerated(attributeEntity)) { object[0] = parseFile.getEnumConditionList(dataTypeString); className = parseFile.getEnumClassName(dataTypeString); } else { // If an entity is of non-enumerated type object[0] = parseFile.getNonEnumConditionList(dataTypeString); className = parseFile.getNonEnumClassName(dataTypeString); } object[1] = attributeEntity; object[2] = new Boolean(showConditions); object[3] = maxLabelDimension; object[4] = true; Object uiObject = null; try { Class[] arr = { ArrayList.class, AttributeInterface.class, Boolean.class, Dimension.class, Boolean.class }; Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getDeclaredConstructor(arr); uiObject = constructor.newInstance(object); } catch (Exception e) { throw new CheckedException(e.getMessage(), e, ErrorCodeConstants.RF_0001); } return uiObject; } public static Object generateUIPanel(ParseXMLFile parseFile, AttributeInterface attributeEntity, Dimension maxLabelDimension) throws CheckedException { return generateUIPanel(parseFile, attributeEntity, true, maxLabelDimension); } /** * This method returns the datatype of the given AttributeTypeInformation * * @param attributeTypeInformation * @return the datatype */ private static String getDataType(AttributeTypeInformationInterface attributeTypeInformation) { String dataTypeString = null; if ((attributeTypeInformation instanceof StringAttributeTypeInformation) || (attributeTypeInformation instanceof ByteArrayAttributeTypeInformation)) { dataTypeString = "string"; } else if ((attributeTypeInformation instanceof IntegerAttributeTypeInformation) || (attributeTypeInformation instanceof LongAttributeTypeInformation) || (attributeTypeInformation instanceof FloatAttributeTypeInformation) || (attributeTypeInformation instanceof DoubleAttributeTypeInformation) || (attributeTypeInformation instanceof NumericAttributeTypeInformation) || (attributeTypeInformation instanceof ShortAttributeTypeInformation)) { dataTypeString = "number"; } else if (attributeTypeInformation instanceof BooleanAttributeTypeInformation) { dataTypeString = "boolean"; } else if (attributeTypeInformation instanceof DateAttributeTypeInformation) { dataTypeString = "date"; } return dataTypeString; } }
package org.elasticsearch.kafka.consumer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import kafka.common.ErrorMapping; import kafka.javaapi.FetchResponse; import kafka.javaapi.message.ByteBufferMessageSet; import kafka.message.Message; import kafka.message.MessageAndOffset; import org.apache.log4j.Logger; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.kafka.consumer.helpers.ExceptionHelper; public class ConsumerJob { private ConsumerConfig consumerConfig; private long offsetForThisRound; private MessageHandler msgHandler; private Client esClient; public KafkaClient kafkaConsumerClient; private Long currentOffsetAtProcess; private Long nextOffsetToProcess; // StatsReporter statsd; // private long statsLastPrintTime; // private Stats stats = new Stats(); private boolean isStartingFirstTime; private String consumerGroupTopicPartition; private LinkedHashMap<Long, Message> offsetMsgMap = new LinkedHashMap<Long, Message>(); private ByteBufferMessageSet byteBufferMsgSet = null; private FetchResponse fetchResponse = null; Logger logger = ConsumerLogger.getLogger(this.getClass()); private int kafkaIntSleepTime = 60000; private int esIntSleepTime = 60000; public LinkedHashMap<Long, Message> getOffsetMsgMap() { return offsetMsgMap; } public void setOffsetMsgMap(LinkedHashMap<Long, Message> offsetMsgMap) { this.offsetMsgMap = offsetMsgMap; } public ConsumerJob(ConsumerConfig config) throws Exception { this.consumerConfig = config; this.isStartingFirstTime = true; this.initKakfa(); this.initElasticSearch(); this.createMessageHandler(); } void initElasticSearch() throws Exception { String[] esHostPortList = this.consumerConfig.esHostPortList.trim() .split(","); logger.info("ElasticSearch HostPortList is:: " + this.consumerConfig.esHostPortList); logger.info("Initializing ElasticSearch"); logger.info("esClusterName is::" + this.consumerConfig.esClusterName); try { Settings settings = ImmutableSettings.settingsBuilder() .put("cluster.name", this.consumerConfig.esClusterName) .build(); for (String eachHostPort : esHostPortList) { logger.info("Setting the Elasticsearch client with :: " + eachHostPort); this.esClient = new TransportClient(settings) .addTransportAddress(new InetSocketTransportAddress( eachHostPort.split(":")[0].trim(), Integer .parseInt(eachHostPort.split(":")[1] .trim()))); } // this.esClient = new // TransportClient(settings).addTransportAddress(new // InetSocketTransportAddress(this.consumerConfig.esHost, // this.consumerConfig.esPort)); logger.info("Initializing ElasticSearch Success. ElasticSearch Client created and intialized."); } catch (Exception e) { logger.fatal("Exception when trying to connect and create ElasticSearch Client. Throwing the error. Error Message is::" + e.getMessage()); throw e; } } void initKakfa() throws Exception { logger.info("Initializing Kafka"); String consumerGroupName = consumerConfig.consumerGroupName; if (consumerGroupName.isEmpty()) { consumerGroupName = "Client_" + consumerConfig.topic + "_" + consumerConfig.partition; logger.info("ConsumerGroupName is empty.Hence created a group name"); } logger.info("consumerGroupName is:" + consumerGroupName); this.consumerGroupTopicPartition = consumerGroupName + "_" + consumerConfig.topic + "_" + consumerConfig.partition; logger.info("consumerGroupTopicPartition is:" + consumerGroupTopicPartition); this.kafkaConsumerClient = new KafkaClient(consumerConfig, consumerConfig.zookeeper, consumerConfig.brokerHost, consumerConfig.brokerPort, consumerConfig.partition, consumerGroupName, consumerConfig.topic); logger.info("Kafka intialization success and kafka client created and intialized"); } void reInitKakfa() throws Exception { logger.info("Kafka Reintialization Kafka & Consumer Client"); this.kafkaConsumerClient.close(); logger.info("Kafka client closed"); logger.info("Connecting to zookeeper again"); this.kafkaConsumerClient.connectToZooKeeper(); logger.info("Completed connecting to zookeeper and finding the new leader now."); this.kafkaConsumerClient.findNewLeader(); logger.info("Found new leader in Kafka broker. Now, initializing the kafka consumer"); this.kafkaConsumerClient.initConsumer(); logger.info("Kafka Reintialization Kafka & Consumer Client is success. Will sleep for " + kafkaIntSleepTime / 1000 + " to allow kafka stabilize"); Thread.sleep(kafkaIntSleepTime); } void reInitElasticSearch() throws Exception { logger.info("Re-Initializing ElasticSearch"); logger.info("Closing ElasticSearch"); this.esClient.close(); logger.info("Completed closing ElasticSearch and starting to initialize again"); this.initElasticSearch(); logger.info("ReInitialized ElasticSearch. Will sleep for " + esIntSleepTime / 1000); Thread.sleep(esIntSleepTime); } public void checkKafkaOffsets() { try { long currentOffset = kafkaConsumerClient .fetchCurrentOffsetFromKafka(); long earliestOffset = kafkaConsumerClient.getEarliestOffset(); long latestOffset = kafkaConsumerClient.getLastestOffset(); logger.info("Kafka offsets: currentOffset=" + currentOffset + "; earliestOffset=" + earliestOffset + "; latestOffset=" + latestOffset); } catch (Exception e) { logger.warn( "Exception from checkKafkaOffsets(): " + e.getMessage(), e); e.printStackTrace(); } } void computeOffset() throws Exception { if (!isStartingFirstTime) { //logger.info("This is not 1st time read in Kafka"); offsetForThisRound = kafkaConsumerClient.fetchCurrentOffsetFromKafka(); if (offsetForThisRound == -1) { throw new Exception( "current offset for this run is -1 which indicates some state corruption; " + " verify expected offset for this topic and restart the app with the CUSTOM offset value; exiting"); } else { logger.info("offsetForThisRound is set to the CurrentOffset: " + offsetForThisRound); } return; } logger.info("**** Starting the Kafka Read for 1st time ***"); logger.info("startOffsetFrom = " + consumerConfig.startOffsetFrom); if (consumerConfig.startOffsetFrom.equalsIgnoreCase("CUSTOM")) { if (consumerConfig.startOffset != -1) { this.offsetForThisRound = consumerConfig.startOffset; } else { throw new Exception( "Custom start offset for " + consumerGroupTopicPartition + " is -1 which is not an acceptable value - please provide a valid offset; exiting"); } } else if (consumerConfig.startOffsetFrom.equalsIgnoreCase("OLDEST")) { this.offsetForThisRound = kafkaConsumerClient.getEarliestOffset(); } else if (consumerConfig.startOffsetFrom.equalsIgnoreCase("LATEST")) { this.offsetForThisRound = kafkaConsumerClient.getLastestOffset(); } else if (consumerConfig.startOffsetFrom.equalsIgnoreCase("RESTART")) { logger.info("ReStarting from where the Offset is left for consumer:" + this.consumerGroupTopicPartition); offsetForThisRound = kafkaConsumerClient.fetchCurrentOffsetFromKafka(); if (offsetForThisRound == -1) { // if this is the first time this client tried to read - offset might be -1 // [ TODO figure out all cases when this can happen] // try to get the Earliest offset and read from there - it may lead // to processing events that may have already be proccesed - but it is safer than // starting from the Latest offset in case not all events were processed before offsetForThisRound = kafkaConsumerClient.getEarliestOffset(); logger.info("offsetForThisRound is set to the EarliestOffset since currentOffset is -1; offsetForThisRound=" + offsetForThisRound); // also store this as the CurrentOffset to Kafka - to avoid the multiple cycles through // this logic in the case no events are coming to the topic for a long time and // we always get currentOffset as -1 from Kafka try { kafkaConsumerClient.saveOffsetInKafka( offsetForThisRound, ErrorMapping.NoError()); } catch (Exception e) { logger.fatal("Failed to commit the offset in Kafka, exiting: " + e.getMessage(), e); throw new Exception("Failed to commit the offset in Kafka, exiting: " + e.getMessage(), e); } } else { logger.info("offsetForThisRound is set to the CurrentOffset: " + offsetForThisRound); } } logger.info("Resulting offsetForThisRound = " + offsetForThisRound); // System.out.println("offsetForThisRound:=" + this.offsetForThisRound); } private void createMessageHandler() throws Exception { try { logger.info("MessageHandler Class given in config is:" + this.consumerConfig.messageHandlerClass); this.msgHandler = (MessageHandler) Class.forName( this.consumerConfig.messageHandlerClass).newInstance(); this.msgHandler.initMessageHandler(this.esClient, this.consumerConfig); logger.info("Created an initialized MessageHandle::" + this.consumerConfig.messageHandlerClass); } catch (Exception e) { e.printStackTrace(); throw e; } } public void doRun() throws Exception { long jobStartTime = System.currentTimeMillis(); boolean esPostResult = false; offsetMsgMap.clear(); this.checkKafkaOffsets(); // TODO fix exception handling - do not re-init Kafka and ES forever - limit to some max # times try { computeOffset(); } catch (Exception e) { logger.error("Exception computing getting Kafka offsets - exiting: ", e); // do not re-init Kafka here for now - re-introduce this once limited number of tries // is implemented - and when it will be clear that re-init-ing of KAfka actually worked // reInitKakfa(); throw e; } // mark this as not first time startup anymore - since we already saved correct offset // to Kafka, and to avoid going through the logic of figuring out the initial offset // every round if it so happens that there were no events from Kafka for a long time if (isStartingFirstTime) { logger.debug("setting 'isStartingFirstTime' to false"); isStartingFirstTime = false; } fetchResponse = kafkaConsumerClient.getFetchResponse( offsetForThisRound, consumerConfig.bulkSize); long timeAfterKafaFetch = System.currentTimeMillis(); logger.info("Fetched the reponse from Kafka. Approx time taken is :: " + (timeAfterKafaFetch - jobStartTime) + " milliSec"); if (fetchResponse.hasError()) { // Do things according to the error code handleError(); return; } // TODO handle failure here byteBufferMsgSet = kafkaConsumerClient.fetchMessageSet(fetchResponse); long timeAftKafaFetchMsgSet = System.currentTimeMillis(); logger.debug("Completed MsgSet fetch from Kafka. Approx time taken is :: " + (timeAftKafaFetchMsgSet - timeAfterKafaFetch) + " milliSec"); if (byteBufferMsgSet.validBytes() <= 0) { logger.warn("No events were read from Kafka - finishing this round of reads from Kafka"); //Thread.sleep(1000); // TODO re-review this logic long latestOffset = kafkaConsumerClient.getLastestOffset(); if (latestOffset != offsetForThisRound) { logger.warn("latestOffset [" + latestOffset + "] is not the same as the current offsetForThisRound for this run [" + offsetForThisRound + "] - committing latestOffset to Kafka"); try { kafkaConsumerClient.saveOffsetInKafka( latestOffset, fetchResponse.errorCode(consumerConfig.topic, consumerConfig.partition)); } catch (Exception e) { // TODO need to handle this exception better logger.fatal("Failed to commit the offset in Kafka - will try later: " + e.getMessage(), e); } } return; } // TODO do not create a second map [offset -> MessageAndOffset] // the info is available in the MEssageAndOffset objects anyway, and no // need to do all this crazy copying/removing from iterators..... Iterator<MessageAndOffset> msgOffSetIter = byteBufferMsgSet.iterator(); while (msgOffSetIter.hasNext()) { MessageAndOffset msgAndOffset = msgOffSetIter.next(); this.currentOffsetAtProcess = msgAndOffset.offset(); this.nextOffsetToProcess = msgAndOffset.nextOffset(); offsetMsgMap.put(currentOffsetAtProcess, msgAndOffset.message()); // msgOffSetIter.remove(); } long timeAftKafkaMsgCollate = System.currentTimeMillis(); logger.debug("Completed collating the Messages and Offset into Map. Approx time taken is::" + (timeAftKafkaMsgCollate - timeAftKafaFetchMsgSet) + " milliSec"); // this.msgHandler.initMessageHandler(); // logger.info("Initialized Message handler"); msgHandler.setOffsetMsgMap(offsetMsgMap); System.out.println("# of message available for this round is:" + offsetMsgMap.size()); logger.info("# of message available for this round is:" + offsetMsgMap.size()); logger.info("Starting to transform the messages"); msgHandler.transformMessage(); logger.info("# of messages which failed during transforming:: " + this.msgHandler.getOffsetFailedMsgMap().size()); logger.info("Completed transforming messages"); //TODO consolidate transformMEssages and prepareToPost....() logger.info("Starting to prepare ElasticSearch"); msgHandler.prepareForPostToElasticSearch(); long timeAtPrepareES = System.currentTimeMillis(); logger.debug("Completed preparing ElasticSearch.Approx time taken to initMsg,TransformMsg,Prepare ES is::" + (timeAtPrepareES - timeAftKafkaMsgCollate) + " milliSec"); logger.debug("nextOffsetToProcess is:: " + nextOffsetToProcess + " This is the offset that will be commited once elasticSearch post is complete"); if (Boolean.parseBoolean(this.consumerConfig.isDryRun.trim())) { logger.info("**** This is a dry run, hence NOT committing the offset in Kafka ****"); return; } try { logger.info("posting the messages to ElasticSearch"); esPostResult = this.msgHandler.postToElasticSearch(); } catch (ElasticsearchException esE) { logger.fatal("ElasticsearchException exception happened. Detailed Message is:: " + esE.getDetailedMessage()); logger.fatal("Root Cause::" + esE.getRootCause()); logger.info("Will try reinitializing ElasticSearch now"); this.reInitElasticSearch(); logger.info("Tried reinitializing ElasticSearch, returning back"); return; } long timeAftEsPost = System.currentTimeMillis(); logger.info("Approx time it took to post of ElasticSearch is:" + (timeAftEsPost - timeAtPrepareES) + " milliSec"); if (!esPostResult) { logger.info("The ES Post failed but we still commit the offset to Kafka - to avoid re-rpocessing the same messages forever"); } else { logger.info("The ES Post is success and this is not a dry run and hence commiting the offset to Kafka"); } logger.info("Commiting offset #:: " + this.nextOffsetToProcess); // TODO optimize getting of the fetchResponse.errorCode - in some places there isno error, // so no need to call the API every time try { this.kafkaConsumerClient.saveOffsetInKafka( this.nextOffsetToProcess, fetchResponse.errorCode( this.consumerConfig.topic, this.consumerConfig.partition)); } catch (Exception e) { logger.fatal("Failed to commit the Offset in Kafka after processing and posting to ES: ", e); logger.info("Trying to reInitialize Kafka and commit the offset again..."); this.reInitKakfa(); try { logger.info("Attempting to commit the offset after reInitializing Kafka now.."); this.kafkaConsumerClient.saveOffsetInKafka( this.nextOffsetToProcess, fetchResponse.errorCode( this.consumerConfig.topic, this.consumerConfig.partition)); } catch (Exception exc) { // KrishnaRaj - Need to handle this situation where // committing offset back to Kafka is failing even after // reInitializing kafka. logger.fatal("Failed to commit the Offset in Kafka even after reInitializing Kafka."); } } long timeAtEndOfJob = System.currentTimeMillis(); logger.info("*** This round of ConsumerJob took approx:: " + (timeAtEndOfJob - jobStartTime) + " milliSec." + "Messages from Offset:" + this.offsetForThisRound + " to " + this.currentOffsetAtProcess + " were processed in this round. ****"); this.byteBufferMsgSet.buffer().clear(); this.byteBufferMsgSet = null; this.fetchResponse = null; } public void handleError() throws Exception { // Do things according to the error code short errorCode = fetchResponse.errorCode( consumerConfig.topic, consumerConfig.partition); logger.error("Error fetching events from Kafka - handling it. Error code: " + errorCode); if (errorCode == ErrorMapping.BrokerNotAvailableCode()) { logger.error("BrokerNotAvailableCode error happened when fetching message from Kafka. ReInitiating Kafka Client"); reInitKakfa(); } else if (errorCode == ErrorMapping.InvalidFetchSizeCode()) { logger.error("InvalidFetchSizeCode error happened when fetching message from Kafka. ReInitiating Kafka Client"); reInitKakfa(); } else if (errorCode == ErrorMapping.InvalidMessageCode()) { logger.error("InvalidMessageCode error happened when fetching message from Kafka, not handling it. Returning."); } else if (errorCode == ErrorMapping.LeaderNotAvailableCode()) { logger.error("LeaderNotAvailableCode error happened when fetching message from Kafka. ReInitiating Kafka Client"); reInitKakfa(); } else if (errorCode == ErrorMapping.MessageSizeTooLargeCode()) { logger.error("MessageSizeTooLargeCode error happened when fetching message from Kafka, not handling it. Returning."); } else if (errorCode == ErrorMapping.NotLeaderForPartitionCode()) { logger.error("NotLeaderForPartitionCode error happened when fetching message from Kafka, not handling it. ReInitiating Kafka Client."); reInitKakfa(); } else if (errorCode == ErrorMapping.OffsetMetadataTooLargeCode()) { logger.error("OffsetMetadataTooLargeCode error happened when fetching message from Kafka, not handling it. Returning."); } else if (errorCode == ErrorMapping.OffsetOutOfRangeCode()) { logger.error("OffsetOutOfRangeCode error happened when fetching message from Kafka"); // It is better not to try to fix this issue programmatically: if the offset is wrong, // either this is the first time we read form Kafka or not - it is better to figure out // why it is wrong and fix the corresponding logic or CUSTOM offset, // rather than blindly reset it to the Latest offset
package org.deepsymmetry.beatlink.data; import org.deepsymmetry.beatlink.*; import org.deepsymmetry.beatlink.dbserver.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.swing.*; import java.io.DataInputStream; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingDeque; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * <p>Watches for new metadata to become available for tracks loaded on players, and queries the * appropriate player for track waveforms when that happens. Can be configured to load only the small waveform * previews, or both those and the full scrollable waveform details.</p> * * <p>Maintains a hot cache of waveforms for any track currently loaded in a player, either on the main playback * deck, or as a hot cue, since those tracks could start playing instantly.</p> * * <p>Implicitly honors the active/passive setting of the {@link MetadataFinder} * (see {@link MetadataFinder#setPassive(boolean)}), because art is loaded in response to metadata updates.</p> * * @author James Elliott */ public class WaveformFinder extends LifecycleParticipant { private static final Logger logger = LoggerFactory.getLogger(WaveformFinder.class); /** * Keeps track of the current waveform previews cached for each player. We hot cache art for any track which is * currently on-deck in the player, as well as any that were loaded into a player's hot-cue slot. */ private final Map<DeckReference, WaveformPreview> previewHotCache = new ConcurrentHashMap<DeckReference, WaveformPreview>(); /** * Keeps track of the current waveform preview cached for each player. We hot cache art for any track which is * currently on-deck in the player, as well as any that were loaded into a player's hot-cue slot. */ private final Map<DeckReference, WaveformDetail> detailHotCache = new ConcurrentHashMap<DeckReference, WaveformDetail>(); /** * Should we ask for details as well as the previews? */ private boolean findDetails = false; /** * Set whether we should retrieve the waveform details in addition to the waveform previews. * * @param findDetails if {@code true}, both types of waveform will be retrieved, if {@code false} only previews * will be retrieved */ public final void setFindDetails(boolean findDetails) { this.findDetails = findDetails; if (findDetails) { primeCache(); // Get details for any tracks that were already loaded on players. } } /** * Check whether we are retrieving the waveform details in addition to the waveform previews. * * @return {@code true} if both types of waveform are being retrieved, {@code false} if only previews * are being retrieved */ @SuppressWarnings("WeakerAccess") public final boolean isFindingDetails() { return findDetails; } /** * A queue used to hold metadata updates we receive from the {@link MetadataFinder} so we can process them on a * lower priority thread, and not hold up delivery to more time-sensitive listeners. */ private final LinkedBlockingDeque<TrackMetadataUpdate> pendingUpdates = new LinkedBlockingDeque<TrackMetadataUpdate>(100); /** * Our metadata listener just puts metadata updates on our queue, so we can process them on a lower * priority thread, and not hold up delivery to more time-sensitive listeners. */ private final TrackMetadataListener metadataListener = new TrackMetadataListener() { @Override public void metadataChanged(TrackMetadataUpdate update) { logger.debug("Received metadata update {}", update); if (!pendingUpdates.offerLast(update)) { logger.warn("Discarding metadata update because our queue is backed up."); } } }; /** * Our mount listener evicts any cached waveforms that belong to media databases which have been unmounted, since * they are no longer valid. */ private final MountListener mountListener = new MountListener() { @Override public void mediaMounted(SlotReference slot) { logger.debug("WaveformFinder doesn't yet need to do anything in response to a media mount."); } @Override public void mediaUnmounted(SlotReference slot) { for (Map.Entry<DeckReference, WaveformPreview> entry : previewHotCache.entrySet()) { if (slot == SlotReference.getSlotReference(entry.getValue().dataReference)) { logger.debug("Evicting cached waveform preview in response to unmount report {}", entry.getValue()); previewHotCache.remove(entry.getKey()); } } for (Map.Entry<DeckReference, WaveformDetail> entry : detailHotCache.entrySet()) { if (slot == SlotReference.getSlotReference(entry.getValue().dataReference)) { logger.debug("Evicting cached waveform detail in response to unmount report {}", entry.getValue()); detailHotCache.remove(entry.getKey()); } } } }; /** * Our announcement listener watches for devices to disappear from the network so we can discard all information * about them. */ private final DeviceAnnouncementListener announcementListener = new DeviceAnnouncementListener() { @Override public void deviceFound(final DeviceAnnouncement announcement) { logger.debug("Currently nothing for WaveformFinder to do when devices appear."); } @Override public void deviceLost(DeviceAnnouncement announcement) { logger.info("Clearing waveforms in response to the loss of a device, {}", announcement); clearWaveforms(announcement); } }; /** * Keep track of whether we are running */ private boolean running = false; /** * Check whether we are currently running. Unless the {@link MetadataFinder} is in passive mode, we will * automatically request waveforms from the appropriate player when a new track is loaded that is not found * in the hot cache or an attached metadata cache file. * * @return true if waveforms are being kept track of for all active players * * @see MetadataFinder#isPassive() */ @SuppressWarnings("WeakerAccess") public synchronized boolean isRunning() { return running; } /** * We process our player status updates on a separate thread so as not to slow down the high-priority update * delivery thread; we perform potentially slow I/O. */ private Thread queueHandler; /** * We have received an update that invalidates the waveform preview for a player, so clear it and alert * any listeners if this represents a change. This does not affect the hot cues; they will stick around until the * player loads a new track that overwrites one or more of them. * * @param update the update which means we have no waveform preview for the associated player */ private void clearDeckPreview(TrackMetadataUpdate update) { if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) { deliverWaveformPreviewUpdate(update.player, null); } } /** * We have received an update that invalidates the waveform detail for a player, so clear it and alert * any listeners if this represents a change. This does not affect the hot cues; they will stick around until the * player loads a new track that overwrites one or more of them. * * @param update the update which means we have no waveform preview for the associated player */ private void clearDeckDetail(TrackMetadataUpdate update) { if (detailHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) { deliverWaveformDetailUpdate(update.player, null); } } /** * We have received an update that invalidates any previous metadata for a player, so clear its waveforms, and alert * any listeners if this represents a change. This does not affect the hot cues; they will stick around until the * player loads a new track that overwrites one or more of them. * * @param update the update which means we have no metadata for the associated player */ private void clearDeck(TrackMetadataUpdate update) { clearDeckPreview(update); clearDeckDetail(update); } private synchronized void clearWaveforms(DeviceAnnouncement announcement) { final int player = announcement.getNumber(); Iterator<DeckReference> deckIterator = previewHotCache.keySet().iterator(); while (deckIterator.hasNext()) { DeckReference deck = deckIterator.next(); if (deck.player == player) { deckIterator.remove(); } } deckIterator = detailHotCache.keySet().iterator(); while (deckIterator.hasNext()) { DeckReference deck = deckIterator.next(); if (deck.player == player) { deckIterator.remove(); } } } /** * We have obtained a waveform preview for a device, so store it and alert any listeners. * * @param update the update which caused us to retrieve this waveform preview * @param preview the waveform preview which we retrieved */ private void updatePreview(TrackMetadataUpdate update, WaveformPreview preview) { previewHotCache.put(DeckReference.getDeckReference(update.player, 0), preview); // Main deck if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well for (CueList.Entry entry : update.metadata.getCueList().entries) { if (entry.hotCueNumber != 0) { previewHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), preview); } } } deliverWaveformPreviewUpdate(update.player, preview); } /** * We have obtained waveform detail for a device, so store it and alert any listeners. * * @param update the update which caused us to retrieve this waveform detail * @param detail the waveform detail which we retrieved */ private void updateDetail(TrackMetadataUpdate update, WaveformDetail detail) { detailHotCache.put(DeckReference.getDeckReference(update.player, 0), detail); // Main deck if (update.metadata.getCueList() != null) { // Update the cache with any hot cues in this track as well for (CueList.Entry entry : update.metadata.getCueList().entries) { if (entry.hotCueNumber != 0) { detailHotCache.put(DeckReference.getDeckReference(update.player, entry.hotCueNumber), detail); } } } deliverWaveformDetailUpdate(update.player, detail); } @SuppressWarnings("WeakerAccess") public Map<DeckReference, WaveformPreview> getLoadedPreviews() { ensureRunning(); // Make a copy so callers get an immutable snapshot of the current state. return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache)); } @SuppressWarnings("WeakerAccess") public Map<DeckReference, WaveformDetail> getLoadedDetails() { ensureRunning(); if (!isFindingDetails()) { throw new IllegalStateException("WaveformFinder is not configured to find waveform details."); } // Make a copy so callers get an immutable snapshot of the current state. return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformDetail>(detailHotCache)); } @SuppressWarnings("WeakerAccess") public WaveformPreview getLatestPreviewFor(int player) { ensureRunning(); return previewHotCache.get(DeckReference.getDeckReference(player, 0)); } public WaveformPreview getLatestPreviewFor(DeviceUpdate update) { return getLatestPreviewFor(update.getDeviceNumber()); } @SuppressWarnings("WeakerAccess") public WaveformDetail getLatestDetailFor(int player) { ensureRunning(); return detailHotCache.get(DeckReference.getDeckReference(player, 0)); } public WaveformDetail getLatestDetailFor(DeviceUpdate update) { return getLatestDetailFor(update.getDeviceNumber()); } /** * Ask the specified player for the waveform preview in the specified slot with the specified rekordbox ID, * using cached media instead if it is available, and possibly giving up if we are in passive mode. * * @param trackReference uniquely identifies the desired waveform preview * @param failIfPassive will prevent the request from taking place if we are in passive mode, so that automatic * waveform updates will use available caches only * * @return the waveform preview found, if any */ private WaveformPreview requestPreviewInternal(final DataReference trackReference, final boolean failIfPassive) { // First check if we are using cached data for this slot ZipFile cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference)); if (cache != null) { return getCachedWaveformPreview(cache, trackReference); } if (MetadataFinder.getInstance().isPassive() && failIfPassive) { // We are not allowed to perform actual requests in passive mode. return null; } // We have to actually request the preview. ConnectionManager.ClientTask<WaveformPreview> task = new ConnectionManager.ClientTask<WaveformPreview>() { @Override public WaveformPreview useClient(Client client) throws Exception { return getWaveformPreview(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client); } }; try { return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, "requesting waveform preview"); } catch (Exception e) { logger.error("Problem requesting waveform preview, returning null", e); } return null; } public WaveformPreview requestWaveformPreviewFrom(final DataReference dataReference) { ensureRunning(); for (WaveformPreview cached : previewHotCache.values()) { if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it. return cached; } } return requestPreviewInternal(dataReference, false); } /** * Look up a waveform preview in a metadata cache. * * @param cache the appropriate metadata cache file * @param dataReference the unique database specification of the desired waveform preview * * @return the cached waveform preview (if available), or {@code null} */ private WaveformPreview getCachedWaveformPreview(ZipFile cache, DataReference dataReference) { ZipEntry entry = cache.getEntry(MetadataFinder.getInstance().getWaveformPreviewEntryName(dataReference.rekordboxId)); if (entry != null) { DataInputStream is = null; try { is = new DataInputStream(cache.getInputStream(entry)); Message message = Message.read(is); return new WaveformPreview(dataReference, message); } catch (IOException e) { logger.error("Problem reading waveform preview from cache file, returning null", e); } finally { if (is != null) { try { is.close(); } catch (Exception e) { logger.error("Problem closing ZipFile input stream for waveform preview", e); } } } } return null; } /** * Requests the waveform preview for a specific track ID, given a connection to a player that has already been * set up. * * @param rekordboxId the track whose waveform preview is desired * @param slot identifies the media slot we are querying * @param client the dbserver client that is communicating with the appropriate player * * @return the retrieved waveform preview, or {@code null} if none was available * @throws IOException if there is a communication problem */ WaveformPreview getWaveformPreview(int rekordboxId, SlotReference slot, Client client) throws IOException { Message response = client.simpleRequest(Message.KnownType.WAVE_PREVIEW_REQ, null, client.buildRMS1(Message.MenuIdentifier.DATA, slot.slot), new NumberField(1), new NumberField(rekordboxId), new NumberField(0)); if (response.knownType == Message.KnownType.WAVE_PREVIEW) { return new WaveformPreview(new DataReference(slot, rekordboxId), response); } logger.error("Unexpected response type when requesting waveform preview: {}", response); return null; } /** * Ask the specified player for the waveform detail in the specified slot with the specified rekordbox ID, * using cached media instead if it is available, and possibly giving up if we are in passive mode. * * @param trackReference uniquely identifies the desired waveform detail * @param failIfPassive will prevent the request from taking place if we are in passive mode, so that automatic * artwork updates will use available caches only * * @return the waveform preview found, if any */ private WaveformDetail requestDetailInternal(final DataReference trackReference, final boolean failIfPassive) { // First check if we are using cached data for this slot ZipFile cache = MetadataFinder.getInstance().getMetadataCache(SlotReference.getSlotReference(trackReference)); if (cache != null) { return getCachedWaveformDetail(cache, trackReference); } if (MetadataFinder.getInstance().isPassive() && failIfPassive) { // We are not allowed to perform actual requests in passive mode. return null; } // We have to actually request the preview. ConnectionManager.ClientTask<WaveformDetail> task = new ConnectionManager.ClientTask<WaveformDetail>() { @Override public WaveformDetail useClient(Client client) throws Exception { return getWaveformDetail(trackReference.rekordboxId, SlotReference.getSlotReference(trackReference), client); } }; try { return ConnectionManager.getInstance().invokeWithClientSession(trackReference.player, task, "requesting waveform detail"); } catch (Exception e) { logger.error("Problem requesting waveform preview, returning null", e); } return null; } public WaveformDetail requestWaveformDetailFrom(final DataReference dataReference) { ensureRunning(); for (WaveformDetail cached : detailHotCache.values()) { if (cached.dataReference.equals(dataReference)) { // Found a hot cue hit, use it. return cached; } } return requestDetailInternal(dataReference, false); } /** * Look up waveform detail in a metadata cache. * * @param cache the appropriate metadata cache file * @param dataReference the unique database specification of the desired waveform detail * * @return the cached waveform detail (if available), or {@code null} */ private WaveformDetail getCachedWaveformDetail(ZipFile cache, DataReference dataReference) { ZipEntry entry = cache.getEntry(MetadataFinder.getInstance().getWaveformDetailEntryName(dataReference.rekordboxId)); if (entry != null) { DataInputStream is = null; try { is = new DataInputStream(cache.getInputStream(entry)); Message message = Message.read(is); return new WaveformDetail(dataReference, message); } catch (IOException e) { logger.error("Problem reading waveform detail from cache file, returning null", e); } finally { if (is != null) { try { is.close(); } catch (Exception e) { logger.error("Problem closing ZipFile input stream for waveform detail", e); } } } } return null; } /** * Requests the waveform detail for a specific track ID, given a connection to a player that has already been * set up. * * @param rekordboxId the track whose waveform detail is desired * @param slot identifies the media slot we are querying * @param client the dbserver client that is communicating with the appropriate player * * @return the retrieved waveform detail, or {@code null} if none was available * @throws IOException if there is a communication problem */ WaveformDetail getWaveformDetail(int rekordboxId, SlotReference slot, Client client) throws IOException { // TODO: Check the details and test this! Message response = client.simpleRequest(Message.KnownType.WAVE_DETAIL_REQ, null, client.buildRMS1(Message.MenuIdentifier.MAIN_MENU, slot.slot), new NumberField(rekordboxId), new NumberField(0)); if (response.knownType == Message.KnownType.WAVE_DETAIL) { return new WaveformDetail(new DataReference(slot, rekordboxId), response); } logger.error("Unexpected response type when requesting waveform detail: {}", response); return null; } /** * Keep track of the devices we are currently trying to get previews from in response to metadata updates. */ private final Set<Integer> activePreviewRequests = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>()); /** * Keep track of the devices we are currently trying to get details from in response to metadata updates. */ private final Set<Integer> activeDetailRequests = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>()); /** * Keeps track of the registered waveform listeners. */ private final Set<WaveformListener> waveformListeners = Collections.newSetFromMap(new ConcurrentHashMap<WaveformListener, Boolean>()); public void addWaveformListener(WaveformListener listener) { if (listener != null) { waveformListeners.add(listener); } } /** * Removes the specified waveform listener so that it no longer receives updates when the * waveform information for a player changes. If {@code listener} is {@code null} or not present * in the set of registered listeners, no exception is thrown and no action is performed. * * @param listener the waveform listener to remove */ public void removeWaveformListener(WaveformListener listener) { if (listener != null) { waveformListeners.remove(listener); } } /** * Get the set of currently-registered waveform listeners. * * @return the listeners that are currently registered for waveform updates */ @SuppressWarnings("WeakerAccess") public Set<WaveformListener> getWaveformListeners() { // Make a copy so callers get an immutable snapshot of the current state. return Collections.unmodifiableSet(new HashSet<WaveformListener>(waveformListeners)); } /** * Send a waveform preview update announcement to all registered listeners. * * @param player the player whose waveform preview has changed * @param preview the new waveform preview, if any */ private void deliverWaveformPreviewUpdate(int player, WaveformPreview preview) { if (!getWaveformListeners().isEmpty()) { final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview); for (final WaveformListener listener : getWaveformListeners()) { try { listener.previewChanged(update); } catch (Exception e) { logger.warn("Problem delivering waveform preview update to listener", e); } } } } /** * Send a waveform detail update announcement to all registered listeners. * @param player the player whose waveform detail has changed * @param detail the new waveform detail, if any */ private void deliverWaveformDetailUpdate(final int player, final WaveformDetail detail) { if (!getWaveformListeners().isEmpty()) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final WaveformDetailUpdate update = new WaveformDetailUpdate(player, detail); for (final WaveformListener listener : getWaveformListeners()) { try { listener.detailChanged(update); } catch (Exception e) { logger.warn("Problem delivering waveform detail update to listener", e); } } } }); } } /** * Process a metadata update from the {@link MetadataFinder}, and see if it means the waveform information * associated with any player has changed. * * @param update describes the new metadata we have for a player, if any */ private void handleUpdate(final TrackMetadataUpdate update) { if (update.metadata == null) { clearDeck(update); } else { // We can offer waveform information for this device; check if we've already looked it up. First, preview: final WaveformPreview lastPreview = previewHotCache.get(DeckReference.getDeckReference(update.player, 0)); if (lastPreview == null || !lastPreview.dataReference.equals(update.metadata.trackReference)) { // We have something new! // First see if we can find the new preview in the hot cache for (WaveformPreview cached : previewHotCache.values()) { if (cached.dataReference.equals(update.metadata.trackReference)) { // Found a hot cue hit, use it. updatePreview(update, cached); return; } } // Not in the cache so try actually retrieving it. if (activePreviewRequests.add(update.player)) { clearDeckPreview(update); // We won't know what it is until our request completes. // We had to make sure we were not already asking for this track. new Thread(new Runnable() { @Override public void run() { try { WaveformPreview preview = requestPreviewInternal(update.metadata.trackReference, true); if (preview != null) { updatePreview(update, preview); } } catch (Exception e) { logger.warn("Problem requesting waveform preview from update" + update, e); } finally { activePreviewRequests.remove(update.player); } } }).start(); } } // Secondly, the detail. final WaveformDetail lastDetail = detailHotCache.get(DeckReference.getDeckReference(update.player, 0)); if (lastDetail == null || !lastDetail.dataReference.equals(update.metadata.trackReference)) { // We have something new! // First see if we can find the new preview in the hot cache for (WaveformDetail cached : detailHotCache.values()) { if (cached.dataReference.equals(update.metadata.trackReference)) { // Found a hot cue hit, use it. updateDetail(update, cached); return; } } // Not in the cache so try actually retrieving it. if (activeDetailRequests.add(update.player)) { clearDeckDetail(update); // We won't know what it is until our request completes. // We had to make sure we were not already asking for this track. new Thread(new Runnable() { @Override public void run() { try { WaveformDetail detail = requestDetailInternal(update.metadata.trackReference, true); if (detail != null) { updateDetail(update, detail); } } catch (Exception e) { logger.warn("Problem requesting waveform detail from update" + update, e); } finally { activeDetailRequests.remove(update.player); } } }).start(); } } } } /** * Set up to automatically stop if anything we depend on stops. */ private final LifecycleListener lifecycleListener = new LifecycleListener() { @Override public void started(LifecycleParticipant sender) { logger.debug("The WaveformFinder does not auto-start when {} does.", sender); } @Override public void stopped(LifecycleParticipant sender) { if (isRunning()) { logger.info("WaveformFinder stopping because {} has.", sender); stop(); } } }; /** * Send ourselves "updates" about any tracks that were loaded before we started, or before we were requesting * details, since we missed them. */ private void primeCache() { for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) { if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck handleUpdate(new TrackMetadataUpdate(entry.getKey().player, entry.getValue())); } } } /** * <p>Start finding waveforms for all active players. Starts the {@link MetadataFinder} if it is not already * running, because we need it to send us metadata updates to notice when new tracks are loaded. This in turn * starts the {@link DeviceFinder}, so we can keep track of the comings and goings of players themselves. * We also start the {@link ConnectionManager} in order to make queries to obtain waveforms.</p> * * @throws Exception if there is a problem starting the required components */ public synchronized void start() throws Exception { if (!running) { ConnectionManager.getInstance().addLifecycleListener(lifecycleListener); ConnectionManager.getInstance().start(); DeviceFinder.getInstance().addDeviceAnnouncementListener(announcementListener); MetadataFinder.getInstance().addLifecycleListener(lifecycleListener); MetadataFinder.getInstance().start(); MetadataFinder.getInstance().addTrackMetadataListener(metadataListener); MetadataFinder.getInstance().addMountListener(mountListener); queueHandler = new Thread(new Runnable() { @Override public void run() { while (isRunning()) { try { handleUpdate(pendingUpdates.take()); } catch (InterruptedException e) { // Interrupted due to MetadataFinder shutdown, presumably } } } }); running = true; queueHandler.start(); deliverLifecycleAnnouncement(logger, true); primeCache(); } } /** * Stop finding waveforms for all active players. */ @SuppressWarnings("WeakerAccess") public synchronized void stop() { if (running) { MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener); running = false; pendingUpdates.clear(); queueHandler.interrupt(); queueHandler = null; for (DeckReference deck : previewHotCache.keySet()) { // Report the loss of our previews. if (deck.hotCue == 0) { deliverWaveformPreviewUpdate(deck.player, null); } } previewHotCache.clear(); for (DeckReference deck : detailHotCache.keySet()) { // Report the loss of our details. if (deck.hotCue == 0) { deliverWaveformDetailUpdate(deck.player, null); } } detailHotCache.clear(); deliverLifecycleAnnouncement(logger, false); } } /** * Holds the singleton instance of this class. */ private static final WaveformFinder ourInstance = new WaveformFinder(); /** * Get the singleton instance of this class. * * @return the only instance of this class which exists. */ public static WaveformFinder getInstance() { return ourInstance; } /** * Prevent direct instantiation. */ private WaveformFinder() { } @Override public String toString() { StringBuilder sb = new StringBuilder("WaveformFinder[running:").append(isRunning()).append(", passive:"); sb.append(MetadataFinder.getInstance().isPassive()).append(", findingDetails:").append(isFindingDetails()); if (isRunning()) { sb.append(", loadedPreviews:").append(getLoadedPreviews()); if (isFindingDetails()) { sb.append(", loadedDetails:").append(getLoadedDetails()); } } return sb.append("]").toString(); } }
package com.hyleria.command; import com.google.inject.Inject; import com.hyleria.command.api.Command; import com.hyleria.command.api.annotation.Permission; import com.hyleria.common.backend.ServerConfig; import com.hyleria.common.backend.payload.StaffChatPayload; import com.hyleria.common.redis.RedisHandler; import com.hyleria.common.redis.api.HandlesType; import com.hyleria.common.reference.Role; import com.hyleria.network.AccountManager; import com.hyleria.network.PermissionManager; import com.hyleria.util.PlayerUtil; import com.hyleria.util.RoleFormat; import com.hyleria.util.TextUtil; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ComponentBuilder; import org.bukkit.Sound; import org.bukkit.entity.Player; /** * @author Ben (OutdatedVersion) * @since Mar/25/2017 (6:45 PM) */ public class StaffChatCommand { /** access accounts */ @Inject private AccountManager accountManager; /** we need to make sure you have the perms to see it */ @Inject private PermissionManager permissionManager; /** name of the server we're on */ private final String serverName; /** deal with redis stuff */ private RedisHandler redis; @Inject public StaffChatCommand(RedisHandler redis, ServerConfig config) { this.serverName = config.name; this.redis = redis.registerHook(this); } @Command ( executor = { "staffchat", "sc" } ) @Permission ( Role.TRIAL ) public void run(Player player, String[] message) { final Role _role = accountManager.grab(player).role(); new StaffChatPayload(player.getName(), _role, RoleFormat.colorFor(_role).name(), TextUtil.arrayToString(message), serverName).publish(redis); } @HandlesType ( StaffChatPayload.class ) public void handleIncoming(StaffChatPayload payload) { // [Staff Chat] final ComponentBuilder _builder = new ComponentBuilder("[Staff Chat]").color(ChatColor.GOLD).bold(true); // [Lobby-1] _builder.append("[" + payload.sentOn + "]").color(ChatColor.DARK_AQUA).bold(false).append(" "); // Dev OutdatedVersion _builder.append(payload.role.name + " " + payload.name).color(ChatColor.valueOf(payload.colorEnum)).append(" "); // message content _builder.append(payload.message).color(ChatColor.AQUA); final BaseComponent[] _message = _builder.create(); PlayerUtil.everyoneStream() .filter(player -> permissionManager.has(player, Role.TRIAL, false)) .forEach(player -> { player.spigot().sendMessage(_message); PlayerUtil.play(player, Sound.NOTE_PLING); }); } }
package org.jboss.msc.service; import java.util.Collection; import java.util.HashSet; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.value.ImmediateValue; import org.jboss.msc.value.Value; /** * {@link BatchServiceTarget} implementation. * * @author <a href="mailto:flavia.rainone@jboss.com">Flavia Rainone</a> * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ class BatchServiceTargetImpl extends DelegatingServiceTarget implements BatchServiceTarget { private final ServiceTarget serviceTarget; private final ServiceRegistry serviceRegistry; private final Collection<ServiceController<?>> addedServiceControllers; BatchServiceTargetImpl(ServiceTarget serviceTarget, ServiceRegistry serviceRegistry) { this(new HashSet<ServiceController<?>>(), serviceTarget.subTarget(), serviceRegistry); } private BatchServiceTargetImpl(Collection<ServiceController<?>> controllers, ServiceTarget serviceTarget, ServiceRegistry serviceRegistry) { super(serviceTarget.subTarget()); this.serviceTarget = serviceTarget; this.serviceRegistry = serviceRegistry; addedServiceControllers = controllers; } @Override public void removeServices() { final Collection<ServiceController<?>> controllers = addedServiceControllers; synchronized(controllers) { for (ServiceController<?> serviceController : controllers) { if (serviceController != null) { serviceController.setMode(Mode.REMOVE); } } controllers.clear(); } } @Override public <T> ServiceBuilder<T> addServiceValue(ServiceName name, Value<? extends Service<T>> value) { return new DelegatingServiceBuilder<T>(super.addServiceValue(name, value)) { public ServiceController<T> install() throws ServiceRegistryException { ServiceController<T> installed = super.install(); final Collection<ServiceController<?>> controllers = addedServiceControllers; synchronized (controllers) { controllers.add(installed); } return installed; } }; } @Override public <T> ServiceBuilder<T> addService(ServiceName name, Service<T> service) { return addServiceValue(name, new ImmediateValue<Service<T>>(service)); } @Override public BatchServiceTarget batchTarget() { return new BatchServiceTargetImpl(serviceTarget, serviceRegistry); } public BatchServiceTarget addListener(final ServiceListener<Object> listener) { super.addListener(listener); return this; } public BatchServiceTarget addListener(final ServiceListener<Object>... listeners) { super.addListener(listeners); return this; } public BatchServiceTarget addListener(final Collection<ServiceListener<Object>> listeners) { super.addListener(listeners); return this; } public BatchServiceTarget removeListener(final ServiceListener<Object> listener) { super.removeListener(listener); return this; } public BatchServiceTarget addDependency(final ServiceName dependency) { super.addDependency(dependency); return this; } public BatchServiceTarget addDependency(final ServiceName... dependencies) { super.addDependency(dependencies); return this; } public BatchServiceTarget addDependency(final Collection<ServiceName> dependencies) { super.addDependency(dependencies); return this; } public BatchServiceTarget removeDependency(final ServiceName dependency) { super.removeDependency(dependency); return this; } public ServiceTarget subTarget() { return new BatchServiceTargetImpl(new HashSet<ServiceController<?>>(), super.subTarget(), serviceRegistry); } }
package org.jenkinsci.plugins.gitclient; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.FilePath; import hudson.ProxyConfiguration; import hudson.Util; import hudson.model.TaskListener; import hudson.plugins.git.Branch; import hudson.plugins.git.GitException; import hudson.plugins.git.GitObject; import hudson.plugins.git.IGitAPI; import hudson.plugins.git.IndexEntry; import hudson.plugins.git.Revision; import hudson.plugins.git.Tag; import hudson.remoting.Channel; import hudson.remoting.RemoteOutputStream; import hudson.remoting.RemoteWriter; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; import javax.annotation.Nonnull; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.io.Writer; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; /** * {@link GitClient} that delegates to a remote {@link GitClient}. * * @author Kohsuke Kawaguchi */ class RemoteGitImpl implements GitClient, IGitAPI, Serializable { private final GitClient proxy; private transient Channel channel; RemoteGitImpl(GitClient proxy) { this.proxy = proxy; } private IGitAPI getGitAPI() { return (IGitAPI)proxy; } private Object readResolve() { channel = Channel.current(); return this; } private Object writeReplace() { if (channel!=null) return proxy; // when sent back to where it came from, switch back to the original object return this; } static class Invocation implements Serializable { private final String methodName; private final String[] parameterTypes; private final Object[] args; Invocation(Method method, @Nonnull Object[] args) { this.methodName = method.getName(); this.args = args; this.parameterTypes = new String[args.length]; Class[] paramTypes = method.getParameterTypes(); for (int i=0; i<args.length; i++) { parameterTypes[i] = paramTypes[i].getName(); } for (int i=0; i<args.length; i++) { if (args[i] instanceof OutputStream) args[i] = new RemoteOutputStream((OutputStream)args[i]); if (args[i] instanceof Writer) args[i] = new RemoteWriter((Writer)args[i]); } } public void replay(Object target) throws InvocationTargetException, IllegalAccessException { OUTER: for (Method m : target.getClass().getMethods()) { if (m.getName().equals(methodName) && m.getParameterTypes().length==parameterTypes.length) { Class<?>[] t = m.getParameterTypes(); for (int i=0; i<parameterTypes.length; i++) { if (!t[i].getName().equals(parameterTypes[i])) continue OUTER; } // matched m.invoke(target,args); return; } } throw new IllegalStateException("Method not found: "+methodName+"("+ Util.join(Arrays.asList(parameterTypes),",")+")"); } private static final long serialVersionUID = 1L; } private <T extends GitCommand> T command(Class<T> type) { return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new CommandInvocationHandler(type,this))); } private static class CommandInvocationHandler implements InvocationHandler, GitCommand, Serializable { private final Class<? extends GitCommand> command; private final List<Invocation> invocations = new ArrayList<>(); private transient final Channel channel; private final GitClient proxy; private CommandInvocationHandler(Class<? extends GitCommand> command, RemoteGitImpl owner) { this.command = command; this.channel = owner.channel; this.proxy = owner.proxy; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class<?> decl = method.getDeclaringClass(); if (args == null) args = new Object[0]; if (GitCommand.class == decl || Object.class==decl) { try { return method.invoke(this,args); } catch (InvocationTargetException e) { throw e.getCause(); } } if (GitCommand.class.isAssignableFrom(decl)) { invocations.add(new Invocation(method, args)); return proxy; } throw new IllegalStateException("Unexpected invocation: "+method); } public void execute() throws GitException, InterruptedException { try { channel.call(new GitCommandMasterToSlaveCallable()); } catch (IOException e) { throw new GitException(e); } } private static final long serialVersionUID = 1L; private class GitCommandMasterToSlaveCallable extends jenkins.security.MasterToSlaveCallable<Void, GitException> { public Void call() throws GitException { try { GitCommand cmd = createCommand(); for (Invocation inv : invocations) { inv.replay(cmd); } cmd.execute(); return null; } catch (InvocationTargetException | IllegalAccessException | InterruptedException e) { throw new GitException(e); } } private GitCommand createCommand() throws InvocationTargetException, IllegalAccessException { for (Method m : GitClient.class.getMethods()) { if (m.getReturnType()==command && m.getParameterTypes().length==0) return command.cast(m.invoke(proxy)); } throw new IllegalStateException("Can't find the factory method for "+command); } } } private OutputStream wrap(OutputStream os) { return new RemoteOutputStream(os); } /** * getRepository. * * @return a {@link org.eclipse.jgit.lib.Repository} object. * @throws hudson.plugins.git.GitException if underlying git operation fails. */ @NonNull public Repository getRepository() throws GitException { throw new UnsupportedOperationException(); } /** * clearCredentials. */ public void clearCredentials() { proxy.clearCredentials(); } /** {@inheritDoc} */ public void addCredentials(String url, StandardCredentials credentials) { proxy.addCredentials(url, CredentialsProvider.snapshot(StandardCredentials.class, credentials)); // credentials are Serializable } /** {@inheritDoc} */ public void setCredentials(StandardUsernameCredentials cred) { proxy.setCredentials(CredentialsProvider.snapshot(StandardUsernameCredentials.class, cred)); // credentials are Serializable } /** {@inheritDoc} */ public void addDefaultCredentials(StandardCredentials credentials) { proxy.addDefaultCredentials(CredentialsProvider.snapshot(StandardCredentials.class, credentials)); // credentials are Serializable } /** {@inheritDoc} */ public void setAuthor(String name, String email) throws GitException { proxy.setAuthor(name, email); } /** {@inheritDoc} */ public void setAuthor(PersonIdent p) throws GitException { proxy.setAuthor(p); } /** {@inheritDoc} */ public void setCommitter(String name, String email) throws GitException { proxy.setCommitter(name, email); } /** {@inheritDoc} */ public void setCommitter(PersonIdent p) throws GitException { proxy.setCommitter(p); } /** {@inheritDoc} */ public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { return proxy.withRepository(callable); } /** * getWorkTree. * * @return a {@link hudson.FilePath} object. */ public FilePath getWorkTree() { return proxy.getWorkTree(); } /** * init. * * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void init() throws GitException, InterruptedException { proxy.init(); } /** {@inheritDoc} */ public void add(String filePattern) throws GitException, InterruptedException { proxy.add(filePattern); } /** {@inheritDoc} */ public void commit(String message) throws GitException, InterruptedException { proxy.commit(message); } /** {@inheritDoc} */ public void commit(String message, PersonIdent author, PersonIdent committer) throws GitException, InterruptedException { proxy.commit(message, author, committer); } /** * hasGitRepo. * * @return true if this workspace has a git repository * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public boolean hasGitRepo() throws GitException, InterruptedException { return proxy.hasGitRepo(); } /** {@inheritDoc} */ public boolean isCommitInRepo(ObjectId commit) throws GitException, InterruptedException { return proxy.isCommitInRepo(commit); } /** {@inheritDoc} */ public String getRemoteUrl(String name) throws GitException, InterruptedException { return proxy.getRemoteUrl(name); } /** {@inheritDoc} */ public void setRemoteUrl(String name, String url) throws GitException, InterruptedException { proxy.setRemoteUrl(name, url); } /** {@inheritDoc} */ public void addRemoteUrl(String name, String url) throws GitException, InterruptedException { proxy.addRemoteUrl(name, url); } /** {@inheritDoc} */ public void checkout(String ref) throws GitException, InterruptedException { proxy.checkout().ref(ref).execute(); } /** {@inheritDoc} */ public void checkout(String ref, String branch) throws GitException, InterruptedException { proxy.checkout().ref(ref).branch(branch).execute(); } /** * checkout. * * @return a {@link org.jenkinsci.plugins.gitclient.CheckoutCommand} object. */ public CheckoutCommand checkout() { return command(CheckoutCommand.class); } /** {@inheritDoc} */ public void checkoutBranch(String branch, String ref) throws GitException, InterruptedException { proxy.checkoutBranch(branch, ref); } /** {@inheritDoc} */ public ObjectId mergeBase(ObjectId sha1, ObjectId sha12) throws InterruptedException { return getGitAPI().mergeBase(sha1, sha12); } /** {@inheritDoc} */ public String getAllLogEntries(String branch) throws InterruptedException { return getGitAPI().getAllLogEntries(branch); } /** {@inheritDoc} */ public List<String> showRevision(Revision r) throws GitException, InterruptedException { return getGitAPI().showRevision(r); } /** {@inheritDoc} */ public void clone(String url, String origin, boolean useShallowClone, String reference) throws GitException, InterruptedException { proxy.clone(url, origin, useShallowClone, reference); } /** * clone_. * * @return a {@link org.jenkinsci.plugins.gitclient.CloneCommand} object. */ public CloneCommand clone_() { return command(CloneCommand.class); } /** * merge. * * @return a {@link org.jenkinsci.plugins.gitclient.MergeCommand} object. */ public MergeCommand merge() { return command(MergeCommand.class); } /** * rebase. * * @return a {@link org.jenkinsci.plugins.gitclient.RebaseCommand} object. */ public RebaseCommand rebase() { return command(RebaseCommand.class); } /** * init_. * * @return a {@link org.jenkinsci.plugins.gitclient.InitCommand} object. */ public InitCommand init_() { return command(InitCommand.class); } /** * fetch_. * * @return a {@link org.jenkinsci.plugins.gitclient.FetchCommand} object. */ public FetchCommand fetch_() { return command(FetchCommand.class); } /** * push. * * @return a {@link org.jenkinsci.plugins.gitclient.PushCommand} object. */ public PushCommand push() { return command(PushCommand.class); } /** * {@inheritDoc} * * @param url a {@link org.eclipse.jgit.transport.URIish} object. * @param refspecs a {@link java.util.List} object. * @throws hudson.plugins.git.GitException if any. * @throws java.lang.InterruptedException if any. */ public void fetch(URIish url, List<RefSpec> refspecs) throws GitException, InterruptedException { proxy.fetch(url, refspecs); } /** {@inheritDoc} */ public void fetch(String remoteName, RefSpec... refspec) throws GitException, InterruptedException { proxy.fetch(remoteName, refspec); } /** {@inheritDoc} */ public void fetch(String remoteName, RefSpec refspec) throws GitException, InterruptedException { fetch(remoteName, new RefSpec[]{refspec}); } /** {@inheritDoc} */ public void push(String remoteName, String refspec) throws GitException, InterruptedException { proxy.push(remoteName, refspec); } /** {@inheritDoc} */ public void push(URIish url, String refspec) throws GitException, InterruptedException { proxy.push(url, refspec); } /** {@inheritDoc} */ public void merge(ObjectId rev) throws GitException, InterruptedException { proxy.merge().setRevisionToMerge(rev).execute(); } /** {@inheritDoc} */ public void prune(RemoteConfig repository) throws GitException, InterruptedException { proxy.prune(repository); } /** * clean. * * @param cleanSubmodule flag to add extra -f * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void clean(boolean cleanSubmodule) throws GitException, InterruptedException { proxy.clean(cleanSubmodule); } /** * clean. * * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void clean() throws GitException, InterruptedException { proxy.clean(); } /** {@inheritDoc} */ public void branch(String name) throws GitException, InterruptedException { proxy.branch(name); } /** {@inheritDoc} */ public void deleteBranch(String name) throws GitException, InterruptedException { proxy.deleteBranch(name); } /** * getBranches. * * @return a {@link java.util.Set} object. * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public Set<Branch> getBranches() throws GitException, InterruptedException { return proxy.getBranches(); } /** * getRemoteBranches. * * @return a {@link java.util.Set} object. * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public Set<Branch> getRemoteBranches() throws GitException, InterruptedException { return proxy.getRemoteBranches(); } /** {@inheritDoc} */ public void tag(String tagName, String comment) throws GitException, InterruptedException { proxy.tag(tagName, comment); } /** {@inheritDoc} */ public boolean tagExists(String tagName) throws GitException, InterruptedException { return proxy.tagExists(tagName); } /** {@inheritDoc} */ public String getTagMessage(String tagName) throws GitException, InterruptedException { return proxy.getTagMessage(tagName); } /** {@inheritDoc} */ public void deleteTag(String tagName) throws GitException, InterruptedException { proxy.deleteTag(tagName); } /** {@inheritDoc} */ public Set<String> getTagNames(String tagPattern) throws GitException, InterruptedException { return proxy.getTagNames(tagPattern); } /** {@inheritDoc} */ public void ref(String refName) throws GitException, InterruptedException { proxy.ref(refName); } /** {@inheritDoc} */ public boolean refExists(String refName) throws GitException, InterruptedException { return proxy.refExists(refName); } /** {@inheritDoc} */ public void deleteRef(String refName) throws GitException, InterruptedException { proxy.deleteRef(refName); } /** {@inheritDoc} */ public Set<String> getRefNames(String refPrefix) throws GitException, InterruptedException { return proxy.getRefNames(refPrefix); } /** {@inheritDoc} */ public Set<String> getRemoteTagNames(String tagPattern) throws GitException, InterruptedException { return proxy.getTagNames(tagPattern); } /** {@inheritDoc} */ public Map<String, ObjectId> getHeadRev(String url) throws GitException, InterruptedException { return proxy.getHeadRev(url); } /** {@inheritDoc} */ public ObjectId getHeadRev(String remoteRepoUrl, String branch) throws GitException, InterruptedException { return proxy.getHeadRev(remoteRepoUrl, branch); } /** {@inheritDoc} */ public Map<String, ObjectId> getRemoteReferences(String remoteRepoUrl, String pattern, boolean headsOnly, boolean tagsOnly) throws GitException, InterruptedException { return proxy.getRemoteReferences(remoteRepoUrl, pattern, headsOnly, tagsOnly); } /** {@inheritDoc} */ public Map<String, String> getRemoteSymbolicReferences(String remoteRepoUrl, String pattern) throws GitException, InterruptedException { return proxy.getRemoteSymbolicReferences(remoteRepoUrl, pattern); } /** {@inheritDoc} */ public ObjectId revParse(String revName) throws GitException, InterruptedException { return proxy.revParse(revName); } /** * revList_. * * @return a {@link org.jenkinsci.plugins.gitclient.RevListCommand} object. */ public RevListCommand revList_() { return proxy.revList_(); } /** * revListAll. * * @return a {@link java.util.List} object. * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public List<ObjectId> revListAll() throws GitException, InterruptedException { return proxy.revListAll(); } /** {@inheritDoc} */ public List<ObjectId> revList(String ref) throws GitException, InterruptedException { return proxy.revList(ref); } /** {@inheritDoc} */ public GitClient subGit(String subdir) { return proxy.subGit(subdir); } /** * hasGitModules. * * @return true if this repository has submodules * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public boolean hasGitModules() throws GitException, InterruptedException { return proxy.hasGitModules(); } /** {@inheritDoc} */ public List<IndexEntry> getSubmodules(String treeIsh) throws GitException, InterruptedException { return proxy.getSubmodules(treeIsh); } /** {@inheritDoc} */ public void addSubmodule(String remoteURL, String subdir) throws GitException, InterruptedException { proxy.addSubmodule(remoteURL, subdir); } /** {@inheritDoc} */ public void submoduleUpdate(boolean recursive) throws GitException, InterruptedException { proxy.submoduleUpdate().recursive(recursive).execute(); } /** * {@inheritDoc} * * @param recursive a boolean. * @param ref a {@link java.lang.String} object. * @throws hudson.plugins.git.GitException if any. * @throws java.lang.InterruptedException if any. */ public void submoduleUpdate(boolean recursive, String ref) throws GitException, InterruptedException { proxy.submoduleUpdate().recursive(recursive).ref(ref).execute(); } /** {@inheritDoc} */ public void submoduleUpdate(boolean recursive, boolean remoteTracking) throws GitException, InterruptedException { proxy.submoduleUpdate().recursive(recursive).remoteTracking(remoteTracking).execute(); } /** {@inheritDoc} */ public void submoduleUpdate(boolean recursive, boolean remoteTracking, String reference) throws GitException, InterruptedException { proxy.submoduleUpdate().recursive(recursive).remoteTracking(remoteTracking).ref(reference).execute(); } /** * submoduleUpdate. * * @return a {@link org.jenkinsci.plugins.gitclient.SubmoduleUpdateCommand} object. */ public SubmoduleUpdateCommand submoduleUpdate() { return command(SubmoduleUpdateCommand.class); } /** {@inheritDoc} */ public void submoduleClean(boolean recursive) throws GitException, InterruptedException { proxy.submoduleClean(recursive); } /** {@inheritDoc} */ public void setupSubmoduleUrls(Revision rev, TaskListener listener) throws GitException, InterruptedException { proxy.setupSubmoduleUrls(rev, listener); } /** {@inheritDoc} */ public void changelog(String revFrom, String revTo, OutputStream os) throws GitException, InterruptedException { proxy.changelog(revFrom, revTo, wrap(os)); } /** * {@inheritDoc} * * @param revFrom a {@link java.lang.String} object. * @param revTo a {@link java.lang.String} object. * @param os a {@link java.io.Writer} object. * @throws hudson.plugins.git.GitException if any. * @throws java.lang.InterruptedException if any. */ public void changelog(String revFrom, String revTo, Writer os) throws GitException, InterruptedException { proxy.changelog(revFrom, revTo, os); // TODO: wrap } /** * changelog. * * @return a {@link org.jenkinsci.plugins.gitclient.ChangelogCommand} object. */ public ChangelogCommand changelog() { return command(ChangelogCommand.class); } /** {@inheritDoc} */ public void appendNote(String note, String namespace) throws GitException, InterruptedException { proxy.appendNote(note, namespace); } /** {@inheritDoc} */ public void addNote(String note, String namespace) throws GitException, InterruptedException { proxy.addNote(note, namespace); } /** {@inheritDoc} */ public List<String> showRevision(ObjectId r) throws GitException, InterruptedException { return proxy.showRevision(r); } /** {@inheritDoc} */ public List<String> showRevision(ObjectId from, ObjectId to) throws GitException, InterruptedException { return proxy.showRevision(from, to); } /** {@inheritDoc} */ public List<String> showRevision(ObjectId from, ObjectId to, Boolean useRawOutput) throws GitException, InterruptedException { return proxy.showRevision(from, to, useRawOutput); } /** {@inheritDoc} */ public boolean hasGitModules(String treeIsh) throws GitException, InterruptedException { return getGitAPI().hasGitModules(treeIsh); } /** {@inheritDoc} */ public String getRemoteUrl(String name, String GIT_DIR) throws GitException, InterruptedException { return getGitAPI().getRemoteUrl(name, GIT_DIR); } /** {@inheritDoc} */ public void setRemoteUrl(String name, String url, String GIT_DIR) throws GitException, InterruptedException { getGitAPI().setRemoteUrl(name, url, GIT_DIR); } /** {@inheritDoc} */ public String getDefaultRemote(String _default_) throws GitException, InterruptedException { return getGitAPI().getDefaultRemote(_default_); } /** * isBareRepository. * * @return true if this repository is bare * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public boolean isBareRepository() throws GitException, InterruptedException { return getGitAPI().isBareRepository(); } /** {@inheritDoc} */ public boolean isBareRepository(String GIT_DIR) throws GitException, InterruptedException { return getGitAPI().isBareRepository(GIT_DIR); } /** * submoduleInit. * * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void submoduleInit() throws GitException, InterruptedException { getGitAPI().submoduleInit(); } /** * submoduleSync. * * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void submoduleSync() throws GitException, InterruptedException { getGitAPI().submoduleSync(); } /** {@inheritDoc} */ public String getSubmoduleUrl(String name) throws GitException, InterruptedException { return getGitAPI().getSubmoduleUrl(name); } /** {@inheritDoc} */ public void setSubmoduleUrl(String name, String url) throws GitException, InterruptedException { getGitAPI().setSubmoduleUrl(name, url); } /** {@inheritDoc} */ public void fixSubmoduleUrls(String remote, TaskListener listener) throws GitException, InterruptedException { getGitAPI().fixSubmoduleUrls(remote, listener); } /** {@inheritDoc} */ public void setupSubmoduleUrls(String remote, TaskListener listener) throws GitException, InterruptedException { getGitAPI().setupSubmoduleUrls(remote, listener); } /** {@inheritDoc} */ public void fetch(String repository, String refspec) throws GitException, InterruptedException { getGitAPI().fetch(repository, refspec); } /** {@inheritDoc} */ public void fetch(RemoteConfig remoteRepository) throws InterruptedException { getGitAPI().fetch(remoteRepository); } /** * fetch. * * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void fetch() throws GitException, InterruptedException { getGitAPI().fetch(); } /** {@inheritDoc} */ public void reset(boolean hard) throws GitException, InterruptedException { getGitAPI().reset(hard); } /** * reset. * * @throws hudson.plugins.git.GitException if underlying git operation fails. * @throws java.lang.InterruptedException if interrupted. */ public void reset() throws GitException, InterruptedException { getGitAPI().reset(); } /** {@inheritDoc} */ public void push(RemoteConfig repository, String revspec) throws GitException, InterruptedException { getGitAPI().push(repository, revspec); } /** {@inheritDoc} */ public void merge(String revSpec) throws GitException, InterruptedException { getGitAPI().merge(revSpec); } /** {@inheritDoc} */ public void clone(RemoteConfig source) throws GitException, InterruptedException { getGitAPI().clone(source); } /** {@inheritDoc} */ public void clone(RemoteConfig rc, boolean useShallowClone) throws GitException, InterruptedException { getGitAPI().clone(rc, useShallowClone); } /** {@inheritDoc} */ public List<Branch> getBranchesContaining(String revspec) throws GitException, InterruptedException { return getGitAPI().getBranchesContaining(revspec); } /** {@inheritDoc} */ public List<IndexEntry> lsTree(String treeIsh) throws GitException, InterruptedException { return getGitAPI().lsTree(treeIsh); } /** {@inheritDoc} */ public List<IndexEntry> lsTree(String treeIsh, boolean recursive) throws GitException, InterruptedException { return getGitAPI().lsTree(treeIsh, recursive); } /** {@inheritDoc} */ public List<ObjectId> revListBranch(String branchId) throws GitException, InterruptedException { return getGitAPI().revListBranch(branchId); } /** {@inheritDoc} */ public String describe(String commitIsh) throws GitException, InterruptedException { return getGitAPI().describe(commitIsh); } /** {@inheritDoc} */ public List<Tag> getTagsOnCommit(String revName) throws GitException, IOException, InterruptedException { return getGitAPI().getTagsOnCommit(revName); } /** {@inheritDoc} */ public void setProxy(ProxyConfiguration proxyConfiguration) { proxy.setProxy(proxyConfiguration); } private static final long serialVersionUID = 1L; /** {@inheritDoc} */ public List<Branch> getBranchesContaining(String revspec, boolean allBranches) throws GitException, InterruptedException { return getGitAPI().getBranchesContaining(revspec, allBranches); } /** {@inheritDoc} */ @Override public Set<GitObject> getTags() throws GitException, InterruptedException { return proxy.getTags(); } }
package org.jtrfp.trcl.pool; import java.beans.PropertyChangeListener; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.NoSuchElementException; import com.ochafik.util.listenable.DefaultListenableCollection; import com.ochafik.util.listenable.ListenableCollection; import com.ochafik.util.listenable.ListenableCollections; import com.ochafik.util.listenable.ListenableList; public class PartitionedIndexPoolImpl<STORED_TYPE> implements PartitionedIndexPool<STORED_TYPE> { private final ListenableList<Partition<STORED_TYPE>> partitions = ListenableCollections.asList(new DefaultListenableCollection<Partition<STORED_TYPE>>(new ArrayList<Partition<STORED_TYPE>>())); private final ListenableCollection<Partition<STORED_TYPE>> partitionsRO = ListenableCollections.unmodifiableCollection(partitions); private final ListenableList<Entry<STORED_TYPE>> flatEntries = ListenableCollections.asList(new DefaultListenableCollection<Entry<STORED_TYPE>>(new ArrayList<Entry<STORED_TYPE>>())); private final ListenableList<Entry<STORED_TYPE>> flatEntriesRO = ListenableCollections.unmodifiableList(flatEntries); private final Deque<Integer>unusedIndices = new ArrayDeque<Integer>(); private int numUsedIndices=0; @Override public org.jtrfp.trcl.pool.PartitionedIndexPool.Partition<STORED_TYPE> newPartition() { Partition<STORED_TYPE> result; //result = new PartitionImpl<STORED_TYPE>(this);//TODO result = null; partitions.add(result); return result; } private int newIndex(){ int result = 0; try{result = unusedIndices.removeFirst();} catch(NoSuchElementException e){ result = numUsedIndices; } numUsedIndices++; return result; }//end newIndex() private void releaseIndex(int index){ unusedIndices.add(index); numUsedIndices } @Override public PartitionedIndexPool<STORED_TYPE> removePartition( org.jtrfp.trcl.pool.PartitionedIndexPool.Partition<STORED_TYPE> toRemove) throws NullPointerException, IllegalArgumentException { if(toRemove==null) throw new NullPointerException(); if(!partitions.contains(toRemove)) throw new IllegalArgumentException(); toRemove.removeAllEntries(); partitions.remove(toRemove); return this; } @Override public PartitionedIndexPool<STORED_TYPE> removeAllPartitions() { for(Partition<STORED_TYPE> partition: partitions) partition.remove(); return this; } @Override public ListenableCollection<org.jtrfp.trcl.pool.PartitionedIndexPool.Partition<STORED_TYPE>> getPartitions() { return partitionsRO; } @Override public ListenableList<Entry<STORED_TYPE>> getFlatEntries() { return flatEntriesRO; } @Override public int getTotalUnusedIndices() { return unusedIndices.size(); } @Override public PartitionedIndexPool<STORED_TYPE> defragment(int maxNumUnusedIndices) throws IllegalArgumentException { return this;//TODO } @Override public org.jtrfp.trcl.pool.PartitionedIndexPool.UnusedIndexLimitBehavior setTotalUnusedLimitBehavior( org.jtrfp.trcl.pool.PartitionedIndexPool.UnusedIndexLimitBehavior behavior) { // TODO Auto-generated method stub return null; } @Override public org.jtrfp.trcl.pool.PartitionedIndexPool.UnusedIndexLimitBehavior getTotalUnusedLimitBehavior() { // TODO Auto-generated method stub return null; } @Override public PartitionedIndexPool<STORED_TYPE> addPropertyChangeListener( PropertyChangeListener l) { // TODO Auto-generated method stub return null; } @Override public PartitionedIndexPool<STORED_TYPE> addPropertyChangeListener( String propertyName, PropertyChangeListener l) { // TODO Auto-generated method stub return null; } @Override public PartitionedIndexPool<STORED_TYPE> removePropertyChangeListener( PropertyChangeListener l) { // TODO Auto-generated method stub return null; } @Override public PartitionedIndexPool<STORED_TYPE> removePropertyChangeListener( String propertyName, PropertyChangeListener l) { // TODO Auto-generated method stub return null; } @Override public PropertyChangeListener[] getPropertyChangeListeners() { // TODO Auto-generated method stub return null; } @Override public PropertyChangeListener[] getPropertyChangeListeners( String propertyName) { // TODO Auto-generated method stub return null; } @Override public boolean hasListeners(String propertyName) { // TODO Auto-generated method stub return false; } }
package org.literacyapp.model.enums.content; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public enum TaskType { LETTER_LISTEN(new HashSet<>(Arrays.asList(LiteracySkill.GRAPHEME_KNOWLEDGE)), null), NUMBER_LISTEN(null, new HashSet<>(Arrays.asList(NumeracySkill.NUMBER_IDENTIFICATION))), TAG_ITEMS(null, new HashSet<>(Arrays.asList(NumeracySkill.ONE_TO_ONE_CORRESPONDENCE))), VIDEO(null, null); public Set<LiteracySkill> literacySkills; public Set<NumeracySkill> numeracySkills; private TaskType(Set<LiteracySkill> literacySkills, Set<NumeracySkill> numeracySkills) { this.literacySkills = literacySkills; this.numeracySkills = numeracySkills; } }
package org.jtrfp.trcl.beh; import org.jtrfp.trcl.beh.DamageableBehavior.HealthNotNeededException; import org.jtrfp.trcl.obj.DEFObject; import org.jtrfp.trcl.obj.WorldObject; public class DestroysEverythingBehavior extends Behavior { int counter=2; boolean replenishingPlayerHealth=true; @Override public void _proposeCollision(WorldObject other){ if(other instanceof DEFObject){ other.getBehavior().probeForBehavior(DamageableBehavior.class).impactDamage(65536);//Really smash that sucker. }//end if(DEFObject) }//end proposeCollision() @Override public void _tick(long timeMillis){ counter if(counter==1&&isReplenishingPlayerHealth()){ try{getParent().getTr().getPlayer().getBehavior().probeForBehavior(DamageableBehavior.class).unDamage();} catch(HealthNotNeededException e){}//Ok, whatever. } if(counter<=0){//We can't stick around for long. Not with all this destroying going on. getParent().destroy();counter=2; }//end if(counter<=0) }//end _tick(...) /** * @return the replenishingPlayerHealth */ public boolean isReplenishingPlayerHealth() { return replenishingPlayerHealth; } /** * @param replenishingPlayerHealth the replenishingPlayerHealth to set */ public DestroysEverythingBehavior setReplenishingPlayerHealth(boolean replenishingPlayerHealth) { this.replenishingPlayerHealth = replenishingPlayerHealth; return this; } }//end DestroyesEverythinBehavior
package org.littleshoot.proxy; import java.lang.Thread.UncaughtExceptionHandler; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HTTP proxy server. */ public class DefaultHttpProxyServer implements HttpProxyServer { private final Logger log = LoggerFactory.getLogger(getClass()); private final ChannelGroup allChannels = new DefaultChannelGroup("HTTP-Proxy-Server"); private final int port; private final ProxyAuthorizationManager authenticationManager = new DefaultProxyAuthorizationManager(); private final Map<String, HttpFilter> filters; private final String chainProxyHostAndPort; /** * Creates a new proxy server. * * @param port The port the server should run on. */ public DefaultHttpProxyServer(final int port) { this(port, new HashMap<String, HttpFilter>()); } public DefaultHttpProxyServer(final int port, final Map<String, HttpFilter> filters) { this(port, filters, null); } /** * Creates a new proxy server. * * @param port The port the server should run on. * @param filters HTTP filters to apply. */ public DefaultHttpProxyServer(final int port, final Map<String, HttpFilter> filters, final String chainProxyHostAndPort) { this.port = port; this.filters = Collections.unmodifiableMap(filters); this.chainProxyHostAndPort = chainProxyHostAndPort; Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(final Thread t, final Throwable e) { log.error("Uncaught exception", e); } }); } public void start() { start(false); } public void start(final boolean localOnly) { log.info("Starting proxy on port: "+this.port); final ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); final HttpServerPipelineFactory factory = new HttpServerPipelineFactory(authenticationManager, this.allChannels, this.filters, this.chainProxyHostAndPort); bootstrap.setPipelineFactory(factory); // Binding only to localhost can significantly improve the security of // the proxy. InetSocketAddress isa; if (localOnly) { isa = new InetSocketAddress("127.0.0.1", port); } else { try { isa = new InetSocketAddress(NetworkUtils.getLocalHost(), port); } catch (final UnknownHostException e) { log.error("Could not get local host?", e); isa = new InetSocketAddress(port); } } final Channel channel = bootstrap.bind(isa); allChannels.add(channel); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { log.info("Shutting down proxy"); final ChannelGroupFuture future = allChannels.close(); future.awaitUninterruptibly(120*1000); bootstrap.releaseExternalResources(); log.info("Done shutting down proxy"); } })); /* final ServerBootstrap sslBootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); sslBootstrap.setPipelineFactory(new HttpServerPipelineFactory()); sslBootstrap.bind(new InetSocketAddress("127.0.0.1", 8443)); */ } public void addProxyAuthenticationHandler( final ProxyAuthorizationHandler pah) { this.authenticationManager.addHandler(pah); } }
package edu.wustl.catissuecore.flex.dag; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Vector; import javax.servlet.http.HttpSession; import edu.common.dynamicextensions.domain.Entity; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException; import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException; import edu.wustl.cab2b.client.ui.dag.PathLink; import edu.wustl.catissuecore.flex.dag.DAGResolveAmbiguity; import edu.wustl.cab2b.client.ui.dag.ambiguityresolver.AmbiguityObject; import edu.wustl.cab2b.client.ui.query.ClientQueryBuilder; import edu.wustl.cab2b.client.ui.query.IClientQueryBuilderInterface; import edu.wustl.cab2b.client.ui.query.IPathFinder; import edu.wustl.cab2b.common.util.Utility; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.bizlogic.querysuite.CreateQueryObjectBizLogic; import edu.wustl.catissuecore.bizlogic.querysuite.GenerateHtmlForAddLimitsBizLogic; import edu.wustl.catissuecore.bizlogic.querysuite.QueryOutputSpreadsheetBizLogic; import edu.wustl.catissuecore.bizlogic.querysuite.QueryOutputTreeBizLogic; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.querysuite.exceptions.CyclicException; import edu.wustl.common.querysuite.exceptions.MultipleRootsException; import edu.wustl.common.querysuite.exceptions.SqlException; import edu.wustl.common.querysuite.factory.QueryObjectFactory; import edu.wustl.common.querysuite.factory.SqlGeneratorFactory; import edu.wustl.common.querysuite.metadata.associations.IAssociation; import edu.wustl.common.querysuite.metadata.path.IPath; import edu.wustl.common.querysuite.queryengine.impl.SqlGenerator; import edu.wustl.common.querysuite.queryobject.ICondition; import edu.wustl.common.querysuite.queryobject.IQueryEntity; import edu.wustl.common.querysuite.queryobject.IConstraints; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IExpressionId; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.querysuite.queryobject.LogicalOperator; import edu.wustl.common.querysuite.queryobject.impl.Expression; import edu.wustl.common.querysuite.queryobject.impl.ExpressionId; import edu.wustl.common.querysuite.queryobject.impl.JoinGraph; import edu.wustl.common.querysuite.queryobject.impl.OutputTreeDataNode; import edu.wustl.common.querysuite.queryobject.impl.Rule; import edu.wustl.common.querysuite.queryobject.util.QueryObjectProcessor; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.logger.Logger; /** *The class is responsibel controlling all activities of Flex DAG * *@author aniket_pandit */ public class DAGPanel { private IClientQueryBuilderInterface m_queryObject; private HttpSession m_session; private IPathFinder m_pathFinder; private IExpression expression; public DAGPanel(IPathFinder pathFinder) { m_pathFinder =pathFinder; } /** * * @param expressionId * @param isOutputView * @return */ private DAGNode createNode(IExpressionId expressionId,boolean isOutputView) { IExpression expression = m_queryObject.getQuery().getConstraints().getExpression(expressionId); IQueryEntity constraintEntity = expression.getQueryEntity(); DAGNode dagNode = new DAGNode(); dagNode.setNodeName(edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity())); dagNode.setExpressionId(expression.getExpressionId().getInt()); if(isOutputView) { dagNode.setNodeType(DAGConstant.VIEW_ONLY_NODE); } else { dagNode.setToolTip(expression); } return dagNode; } @SuppressWarnings("unchecked") public DAGNode createQueryObject(String strToCreateQueryObject,String entityName,String mode) { Map ruleDetailsMap = null; IExpressionId expressionId = null; DAGNode node = null; //IQuery query = (IQuery)session.getAttribute(AppletConstants.QUERY_OBJECT); IQuery query = m_queryObject.getQuery(); System.out.println("query=======>"+query); m_session.setAttribute(AppletConstants.QUERY_OBJECT, query); try { //IQuery query = getQueryObjectFromServer(); Get exiting Query object from server // if(query != null) // queryObject.setQuery(query); // DAGNodeBuilder nodeBuilder = new DAGNodeBuilder(); Map searchedEntitiesMap = (Map)m_session.getAttribute(Constants.SEARCHED_ENTITIES_MAP); EntityInterface entity = (Entity) searchedEntitiesMap.get(entityName); CreateQueryObjectBizLogic queryBizLogic = new CreateQueryObjectBizLogic(); if (!strToCreateQueryObject.equalsIgnoreCase("")) { ruleDetailsMap = queryBizLogic.getRuleDetailsMap(strToCreateQueryObject, entity); List<AttributeInterface> attributes = (List<AttributeInterface>) ruleDetailsMap.get(AppletConstants.ATTRIBUTES); List<String> attributeOperators = (List<String>) ruleDetailsMap.get(AppletConstants.ATTRIBUTE_OPERATORS); List<List<String>> conditionValues = (List<List<String>>) ruleDetailsMap.get(AppletConstants.ATTR_VALUES); if(mode.equals("Edit")) { Rule rule = ((Rule) (expression.getOperand(0))); rule.removeAllConditions(); List<ICondition> conditionsList = ((ClientQueryBuilder)m_queryObject).getConditions(attributes, attributeOperators,conditionValues); for (ICondition condition : conditionsList) { rule.addCondition(condition); } expressionId = expression.getExpressionId(); node = createNode(expressionId,false); } else { expressionId = m_queryObject.addRule(attributes, attributeOperators, conditionValues); node = createNode(expressionId,false); } } } catch (DynamicExtensionsSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DynamicExtensionsApplicationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return node; } /** * Sets ClientQueryBuilder object * @param queryObject */ public void setQueryObject(IClientQueryBuilderInterface queryObject) { m_queryObject = queryObject; } /** * Sets httpsession * @param session */ public void setSession(HttpSession session) { m_session=session; } /** * Sets Expression * @param expression */ public void setExpression(IExpression expression) { this.expression = expression; } /** * Links two nodes * @param sourceNode * @param destNode * @param paths */ public void linkNode(final DAGNode sourceNode, final DAGNode destNode,List<IPath> paths) { try { // if (paths == null || paths.isEmpty()) { // JOptionPane.showMessageDialog(MainDagPanel.this, // "No path available/selected between source and destination categories", // "Connect Nodes warning", JOptionPane.WARNING_MESSAGE); // return; IExpressionId sourceExpressionId = new ExpressionId(sourceNode.getExpressionId()); IExpressionId destExpressionId = new ExpressionId(destNode.getExpressionId()); if (!m_queryObject.isPathCreatesCyclicGraph(sourceExpressionId, destExpressionId, paths.get(0))) { for (int i = 0; i < paths.size(); i++) { LinkTwoNode(sourceNode, destNode, paths.get(i), new ArrayList<IExpressionId>()); } } // else { // JOptionPane.showMessageDialog(MainDagPanel.this, // "Cannot connect selected nodes as it creates cycle in the query graph", // "Connect Nodes warning", JOptionPane.WARNING_MESSAGE); } catch (Exception e) { e.printStackTrace(); } } /** * Gets list of paths between two nodes * @param sourceNode * @param destNode * @return */ public List<IPath> getPaths(DAGNode sourceNode, DAGNode destNode) { Map<AmbiguityObject, List<IPath>> map = null; AmbiguityObject ambiguityObject = null; try { IQuery query = m_queryObject.getQuery(); IConstraints constraints = query.getConstraints(); IExpressionId expressionId = new ExpressionId(sourceNode.getExpressionId()); IExpression expression = constraints .getExpression(expressionId); IQueryEntity sourceEntity = expression .getQueryEntity(); expressionId = new ExpressionId(destNode.getExpressionId()); expression = constraints.getExpression(expressionId); IQueryEntity destinationEntity = expression .getQueryEntity(); ambiguityObject = new AmbiguityObject( sourceEntity.getDynamicExtensionsEntity(), destinationEntity.getDynamicExtensionsEntity()); // ResolveAmbiguity resolveAmbigity = new ResolveAmbiguity( // ambiguityObject, m_pathFinder); DAGResolveAmbiguity resolveAmbigity = new DAGResolveAmbiguity(ambiguityObject, m_pathFinder); map = resolveAmbigity.getPathsForAllAmbiguities(); } catch (Exception e) { e.printStackTrace(); } return map.get(ambiguityObject); } /** * Link 2 nodes * @param sourceNode * @param destNode * @param path * @param intermediateExpressions */ private void LinkTwoNode(final DAGNode sourceNode, final DAGNode destNode, final IPath path, List<IExpressionId> intermediateExpressions) { PathLink link = getPathLink(sourceNode, destNode, path, intermediateExpressions); //// if (assPosition == 0) { //// updateQueryObject(link, sourceNode, destNode, null); //// } else { updateQueryObject(link,sourceNode, destNode); } private PathLink getPathLink(final DAGNode sourceNode, final DAGNode destNode, final IPath path, List<IExpressionId> intermediateExpressions) { IExpressionId sourceexpressionId = null; IExpressionId destexpressionId = null; try { sourceexpressionId = new ExpressionId(sourceNode .getExpressionId()); destexpressionId = new ExpressionId(destNode .getExpressionId()); intermediateExpressions = m_queryObject.addPath(sourceexpressionId, destexpressionId, path); } catch (CyclicException e) { // JOptionPane.showMessageDialog(this, "Cannot connect nodes as it creates cycle in graph", // "Connect Nodes warning", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } PathLink link = new PathLink(); link.setAssociationExpressions(intermediateExpressions); link.setDestinationExpressionId(destexpressionId); link.setSourceExpressionId(sourceexpressionId); link.setPath(path); return link; } /** * Updates query object * @param link * @param sourceNode * @param destNode */ private void updateQueryObject(PathLink link, DAGNode sourceNode, DAGNode destNode) { IExpressionId sourceexpressionId = new ExpressionId(sourceNode .getExpressionId()); IExpressionId destexpressionId = new ExpressionId(destNode .getExpressionId()); // If the first association is added, put operator between attribute condition and association String operator = null; // if (sourcePort == null) { operator = sourceNode.getOperatorBetweenAttrAndAssociation(); //} else { // Get the logical operator associated with previous association // operator = sourceNode.getLogicalOperator(sourcePort); // Get the expressionId between which to add logical operator IExpressionId destId = link.getLogicalConnectorExpressionId(); m_queryObject.setLogicalConnector(sourceexpressionId, destId, edu.wustl.cab2b.client.ui.query.Utility.getLogicalOperator(operator), false); // Put appropriate parenthesis //if (sourcePort != null) { IExpressionId previousExpId = link.getLogicalConnectorExpressionId(); m_queryObject.addParantheses(sourceexpressionId, previousExpId, destId); } /** * Gets display path string * @param path * @return */ public static String getPathDisplayString(IPath path) { String text = "Path:"; // text=text.concat("<HTML><B>Path</B>:"); List<IAssociation> pathList = path.getIntermediateAssociations(); text = text.concat(Utility.getDisplayName(path.getSourceEntity())); for (int i = 0; i < pathList.size(); i++) { text = text.concat(" text = text.concat(Utility.getDisplayName(pathList.get(i).getTargetEntity())); } text = text.concat(""); Logger.out.debug(text); StringBuffer sb = new StringBuffer(); int textLength = text.length(); Logger.out.debug(textLength); int currentStart = 0; String currentString = null; int offset = 100; int strLen = 0; int len = 0; while (currentStart < textLength && textLength > offset) { currentString = text.substring(currentStart, (currentStart + offset)); strLen = strLen + currentString.length() + len; sb.append(currentString); int index = text.indexOf("--->", (currentStart + offset)); if (index == -1) { index = text.indexOf(".", (currentStart + offset)); } if (index == -1) { index = text.indexOf(",", (currentStart + offset)); } if (index == -1) { index = text.indexOf(" ", (currentStart + offset)); } if (index != -1) { len = index - strLen; currentString = text.substring((currentStart + offset), (currentStart + offset + len)); sb.append(currentString); sb.append(""); } else { if (currentStart == 0) { currentStart = offset; } sb.append(text.substring(currentStart)); return sb.toString(); } currentStart = currentStart + offset + len; if ((currentStart + offset + len) > textLength) break; } sb.append(text.substring(currentStart)); return sb.toString(); } /** * Generates sql query * @return */ public String search() { String message=null; try { int recordsPerPage; String recordsPerPageSessionValue = (String)m_session.getAttribute(Constants.RESULTS_PER_PAGE); if (recordsPerPageSessionValue==null) { recordsPerPage = Integer.parseInt(XMLPropertyHandler.getValue(Constants.RECORDS_PER_PAGE_PROPERTY_NAME)); m_session.setAttribute(Constants.RESULTS_PER_PAGE, recordsPerPage+""); } else recordsPerPage = new Integer(recordsPerPageSessionValue).intValue(); boolean isRulePresentInDag = false; IQuery query = m_queryObject.getQuery(); SqlGenerator sql = new SqlGenerator(); try { System.out.println("Query: [ " + sql.generateSQL(query)+" ]"); } catch (SqlException e) { // TODO Auto-generated catch block e.printStackTrace(); } IConstraints constraints = query.getConstraints(); Enumeration<IExpressionId> expressionIds = constraints.getExpressionIds(); while(expressionIds.hasMoreElements()) { IExpressionId id = expressionIds.nextElement(); if(((Expression)constraints.getExpression(id)).containsRule()) { isRulePresentInDag = true; break; } } if(isRulePresentInDag) { m_session.setAttribute(AppletConstants.QUERY_OBJECT, query); String selectSql = ""; SqlGenerator sqlGenerator = (SqlGenerator)SqlGeneratorFactory.getInstance(); QueryOutputTreeBizLogic outputTreeBizLogic = new QueryOutputTreeBizLogic(); selectSql = sqlGenerator.generateSQL(query); Object obj = m_session.getAttribute(Constants.SESSION_DATA); if (obj != null) { SessionDataBean sessionData = (SessionDataBean) obj; outputTreeBizLogic.createOutputTreeTable(selectSql, sessionData); //Map<OutputTreeDataNode,Map<Long, Map<AttributeInterface, String>>> outputTreeMap = sqlGenerator.getOutputTreeMap(); List<OutputTreeDataNode> rootOutputTreeNodeList = sqlGenerator.getRootOutputTreeNodeList(); m_session.setAttribute(Constants.TREE_ROOTS,rootOutputTreeNodeList); //Set<OutputTreeDataNode> keys = outputTreeMap.keySet(); Long noOfTrees = new Long(rootOutputTreeNodeList.size()); m_session.setAttribute(Constants.NO_OF_TREES, noOfTrees); Map<String, OutputTreeDataNode> uniqueIdNodesMap = QueryObjectProcessor.getAllChildrenNodes(rootOutputTreeNodeList); m_session.setAttribute(Constants.ID_NODES_MAP, uniqueIdNodesMap); int i =0; for(OutputTreeDataNode node :rootOutputTreeNodeList) { Vector treeData = outputTreeBizLogic.createDefaultOutputTreeData(i,node, sessionData); m_session.setAttribute(Constants.TREE_DATA+"_"+i, treeData); i += 1; } OutputTreeDataNode node = rootOutputTreeNodeList.get(0); QueryOutputSpreadsheetBizLogic outputSpreadsheetBizLogic = new QueryOutputSpreadsheetBizLogic(); String parentNodeId = null; String treeNo = "0"; Map spreadSheetDatamap = outputSpreadsheetBizLogic.createSpreadsheetData(treeNo,node, sessionData,parentNodeId,recordsPerPage); m_session.setAttribute(Constants.SPREADSHEET_DATA_LIST, spreadSheetDatamap.get(Constants.SPREADSHEET_DATA_LIST)); m_session.setAttribute(Constants.SPREADSHEET_COLUMN_LIST, spreadSheetDatamap.get(Constants.SPREADSHEET_COLUMN_LIST)); message ="SUCCESS"; } else { message = AppletConstants.EMPTY_DAG_ERROR_MESSAGE; } } } catch (MultipleRootsException e) { e.printStackTrace(); } catch (SqlException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (DAOException e) { e.printStackTrace(); } return message; } /** * Repaints DAG * @return */ public List<DAGNode> repaintDAG() { List<DAGNode> nodeList = new ArrayList<DAGNode>(); IQuery query =(IQuery)m_session.getAttribute("queryObject"); IConstraints constraints = query.getConstraints(); HashSet<IExpressionId> visibleExpression = new HashSet<IExpressionId>(); Enumeration<IExpressionId> expressionIds = constraints.getExpressionIds(); while(expressionIds.hasMoreElements()) { IExpressionId id = expressionIds.nextElement(); IExpression expression = constraints.getExpression(id); if(expression.isVisible()) { visibleExpression.add(id); } } for(IExpressionId expressionId:visibleExpression){ IExpression exp = constraints.getExpression(expressionId); IQueryEntity constraintEntity = exp.getQueryEntity(); String nodeDisplayName = edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity()); DAGNode dagNode = new DAGNode(); dagNode.setExpressionId(exp.getExpressionId().getInt()); dagNode.setNodeName(nodeDisplayName); dagNode.setToolTip(exp); if(!exp.containsRule()) { dagNode.setNodeType(DAGConstant.VIEW_ONLY_NODE); } if(!exp.isInView()) { dagNode.setNodeType(DAGConstant.CONSTRAINT_ONLY_NODE); } nodeform(expressionId,dagNode,constraints,nodeDisplayName); int numOperands = exp.numberOfOperands(); int numOperator = numOperands-1; for(int i=0;i<numOperator;i++) { String operator = exp.getLogicalConnector(i, i+1).getLogicalOperator().toString(); dagNode.setOperatorList(operator.toUpperCase()); } nodeList.add(dagNode); } return nodeList; } private void nodeform(IExpressionId expressionId,DAGNode node,IConstraints constraints,String path) { List childList = constraints.getJoinGraph().getChildrenList(expressionId); for(int i=0;i<childList.size();i++) { String nodeDisplayName = ""; IExpressionId newId = (IExpressionId)childList.get(i); IExpression exp = constraints.getExpression(newId); IQueryEntity constraintEntity = exp.getQueryEntity(); if(exp.isVisible()) { nodeDisplayName =edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity()); path = path + "--->"+nodeDisplayName; DAGNode dagNode = new DAGNode(); dagNode.setExpressionId(exp.getExpressionId().getInt()); dagNode.setNodeName(edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity())); dagNode.setToolTip(exp); node.setAssociationList(dagNode); node.setPathList(path); } else { nodeDisplayName =edu.wustl.cab2b.common.util.Utility.getOnlyEntityName(constraintEntity.getDynamicExtensionsEntity()); path = path + "--->"+nodeDisplayName; nodeform(newId,node,constraints,path); } } } public void updateLogicalOperator(int parentExpId,int parentIndex,String operator ) { IExpressionId parentExpressionId = new ExpressionId(parentExpId); IQuery query = m_queryObject.getQuery(); IExpression parentExpression = query.getConstraints().getExpression(parentExpressionId); LogicalOperator logicOperator = edu.wustl.cab2b.client.ui.query.Utility.getLogicalOperator(operator); int childIndex = parentIndex +1; parentExpression.setLogicalConnector(parentIndex, childIndex,QueryObjectFactory.createLogicalConnector(logicOperator)); m_queryObject.setQuery(query); } public Map editAddLimitUI(int expId) { Map<String, Object> map = new HashMap<String,Object>(); IExpressionId expressionId = new ExpressionId(expId); IExpression expression = m_queryObject.getQuery().getConstraints().getExpression(expressionId); EntityInterface entity = expression.getQueryEntity().getDynamicExtensionsEntity(); GenerateHtmlForAddLimitsBizLogic generateHTMLBizLogic = new GenerateHtmlForAddLimitsBizLogic(); Rule rule = ((Rule) (expression.getOperand(0))); List<ICondition> conditions = rule.getConditions(); String html = generateHTMLBizLogic.generateHTML(entity, conditions); map.put(DAGConstant.HTML_STR, html); map.put(DAGConstant.EXPRESSION, expression); return map; } public DAGNode addNodeToOutPutView(String nodesStr) { DAGNode node = null; if (!nodesStr.equalsIgnoreCase("")) { if(nodesStr.indexOf("~")!= -1) { String[] entityArr = nodesStr.split("~"); Map entityMap = (Map)m_session.getAttribute(Constants.SEARCHED_ENTITIES_MAP); for(int i=0;i<entityArr.length; i++) { String entityName = entityArr[i]; EntityInterface entity = (EntityInterface)entityMap.get(entityName); IExpressionId expressionId = ((ClientQueryBuilder)m_queryObject).addExpression(entity); // DAGNodeBuilder nodeBuilder = new DAGNodeBuilder(); node = createNode(expressionId,true); } } } return node; } public void restoreQueryObject() { IQuery query =m_queryObject.getQuery(); int roots = ((JoinGraph)(query.getConstraints().getJoinGraph())).getAllRoots().size(); if(roots > 1) { //errorMessage = AppletConstants.MULTIPLE_ROOTS_EXCEPTION; // showValidationMessagesToUser(errorMessage); } else { m_session.setAttribute(AppletConstants.QUERY_OBJECT, query); } } public void deleteExpression(int expId) { IExpressionId expressionId = new ExpressionId(expId); m_queryObject.removeExpression(expressionId); //m_queryObject.setQuery(arg0) } public void addExpressionToView(int expId) { IExpressionId expressionId = new ExpressionId(expId); Expression expression = (Expression) m_queryObject.getQuery().getConstraints().getExpression(expressionId); expression.setInView(true); } public void deleteExpressionFormView(int expId) { IExpressionId expressionId = new ExpressionId(expId); Expression expression = (Expression) m_queryObject.getQuery().getConstraints().getExpression(expressionId); expression.setInView(false); } public void deletePath(IPath path,List<DAGNode>linkedNodeList) { PathLink link = getPathLink(linkedNodeList.get(0),linkedNodeList.get(1) , path, new ArrayList<IExpressionId>()); List<IExpressionId> expressionIds = link.getAssociationExpressions(); // If the association is direct association, remove the respective association if (0 == expressionIds.size()) { m_queryObject.removeAssociation(link.getSourceExpressionId(), link.getDestinationExpressionId()); } else { for (int i = 0; i < expressionIds.size(); i++) { m_queryObject.removeExpression(expressionIds.get(i)); } } } }
package org.menina.redis.adapter.balance; import java.util.List; public class HashBalance<T> extends AbstractBalance<T>{ @Override public void setProviders(List<T> providers) { this.providers = providers; } @Override public T getNode() { // int index = condition.hashCode() % this.providers.size(); // return this.providers.get(index); return null; } }
package org.libre.lingvo.config; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; import java.util.Properties; @Configuration @Profile("cloud") public class CloudDataSourceConfig extends AbstractCloudConfig { @Bean public DataSource dataSource() { DataSource dataSource = connectionFactory().dataSource(); if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) { /*org.apache.tomcat.jdbc.pool.DataSource tomcatDatasource = (org.apache.tomcat.jdbc.pool.DataSource) dataSource; tomcatDatasource.setConnectionProperties("useUnicode=yes;characterEncoding=utf8;");*/ String url = ((org.apache.tomcat.jdbc.pool.DataSource) dataSource).getUrl(); DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(url); Properties properties = new Properties(); properties.put("useUnicode", "yes"); properties.put("characterEncoding", "utf8"); driverManagerDataSource.setConnectionProperties(properties); dataSource = driverManagerDataSource; } return dataSource; } }
package org.literacyapp.model.gson.content; import java.util.List; public class NumberGson extends ContentGson { private Integer value; private String symbol; @Deprecated private WordGson word; private List<WordGson> words; public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } @Deprecated public WordGson getWord() { return word; } @Deprecated public void setWord(WordGson word) { this.word = word; } public List<WordGson> getWords() { return words; } public void setWords(List<WordGson> words) { this.words = words; } }
package org.openlmis.fulfillment.web; import static org.openlmis.fulfillment.domain.OrderStatus.ORDERED; import static org.openlmis.fulfillment.domain.OrderStatus.SHIPPED; import static org.openlmis.fulfillment.domain.OrderStatus.TRANSFER_FAILED; import static org.openlmis.fulfillment.i18n.MessageKeys.ERROR_ORDER_INVALID_STATUS; import static org.openlmis.fulfillment.i18n.MessageKeys.ERROR_ORDER_RETRY_INVALID_STATUS; import org.openlmis.fulfillment.domain.Order; import org.openlmis.fulfillment.domain.OrderFileTemplate; import org.openlmis.fulfillment.domain.OrderNumberConfiguration; import org.openlmis.fulfillment.repository.OrderNumberConfigurationRepository; import org.openlmis.fulfillment.repository.OrderRepository; import org.openlmis.fulfillment.service.ConfigurationSettingException; import org.openlmis.fulfillment.service.FulfillmentException; import org.openlmis.fulfillment.service.OrderCsvHelper; import org.openlmis.fulfillment.service.OrderFileException; import org.openlmis.fulfillment.service.OrderFileTemplateService; import org.openlmis.fulfillment.service.OrderService; import org.openlmis.fulfillment.service.OrderStorageException; import org.openlmis.fulfillment.service.PermissionService; import org.openlmis.fulfillment.service.referencedata.ProgramDto; import org.openlmis.fulfillment.service.referencedata.ProgramReferenceDataService; import org.openlmis.fulfillment.web.util.OrderDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import java.io.IOException; import java.util.UUID; import javax.servlet.http.HttpServletResponse; @Controller public class OrderController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class); private static final String DISPOSITION_BASE = "attachment; filename="; @Autowired private OrderRepository orderRepository; @Autowired private OrderService orderService; @Autowired private OrderCsvHelper csvHelper; @Autowired private OrderFileTemplateService orderFileTemplateService; @Autowired private PermissionService permissionService; @Autowired private ProgramReferenceDataService programReferenceDataService; @Autowired private OrderNumberConfigurationRepository orderNumberConfigurationRepository; /** * Allows creating new orders. * If the id is specified, it will be ignored. * * @param orderDto A order bound to the request body * @return ResponseEntity containing the created order */ @RequestMapping(value = "/orders", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public OrderDto createOrder(@RequestBody OrderDto orderDto, OAuth2Authentication authentication) throws ConfigurationSettingException, OrderStorageException, MissingPermissionException { Order order = Order.newInstance(orderDto); if (!authentication.isClientOnly()) { LOGGER.debug("Checking rights to create order"); permissionService.canConvertToOrder(order); } LOGGER.debug("Creating new order"); ProgramDto program = programReferenceDataService.findOne(order.getProgramId()); OrderNumberConfiguration orderNumberConfiguration = orderNumberConfigurationRepository.findAll().iterator().next(); order.setId(null); order.setOrderCode(orderNumberConfiguration.generateOrderNumber(order, program)); Order newOrder = orderService.save(order); LOGGER.debug("Created new order with id: {}", order.getId()); return OrderDto.newInstance(newOrder); } /** * Get all orders. * * @return OrderDtos. */ @RequestMapping(value = "/orders", method = RequestMethod.GET) @ResponseBody public Iterable<OrderDto> getAllOrders() { return OrderDto.newInstance(orderRepository.findAll()); } /** * Allows updating orders. * * @param orderDto A order bound to the request body * @param orderId UUID of order which we want to update * @return ResponseEntity containing the updated order */ @RequestMapping(value = "/orders/{id}", method = RequestMethod.PUT) @ResponseBody public OrderDto updateOrder(@RequestBody OrderDto orderDto, @PathVariable("id") UUID orderId) { Order orderToUpdate = orderRepository.findOne(orderId); if (orderToUpdate == null) { orderToUpdate = new Order(); LOGGER.info("Creating new order"); } else { LOGGER.debug("Updating order with id: {}", orderId); } Order order = Order.newInstance(orderDto); orderToUpdate.updateFrom(order); orderToUpdate = orderRepository.save(orderToUpdate); LOGGER.debug("Saved order with id: {}", orderToUpdate.getId()); return OrderDto.newInstance(orderToUpdate); } /** * Get chosen order. * * @param orderId UUID of order whose we want to get * @return OrderDto. */ @RequestMapping(value = "/orders/{id}", method = RequestMethod.GET) public ResponseEntity<OrderDto> getOrder(@PathVariable("id") UUID orderId) { Order order = orderRepository.findOne(orderId); if (order == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { return new ResponseEntity<>(OrderDto.newInstance(order), HttpStatus.OK); } } /** * Allows deleting order. * * @param orderId UUID of order which we want to delete * @return ResponseEntity containing the HTTP Status */ @RequestMapping(value = "/orders/{id}", method = RequestMethod.DELETE) public ResponseEntity<OrderDto> deleteOrder(@PathVariable("id") UUID orderId) { Order order = orderRepository.findOne(orderId); if (order == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { orderRepository.delete(order); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } /** * Finds Orders matching all of provided parameters. * * @param supplyingFacility supplyingFacility of searched Orders. * @param requestingFacility requestingFacility of searched Orders. * @param program program of searched Orders. * @return ResponseEntity with list of all Orders matching provided parameters and OK httpStatus. */ @RequestMapping(value = "/orders/search", method = RequestMethod.GET) @ResponseBody public Iterable<OrderDto> searchOrders( @RequestParam(value = "supplyingFacility") UUID supplyingFacility, @RequestParam(value = "requestingFacility", required = false) UUID requestingFacility, @RequestParam(value = "program", required = false) UUID program) { return OrderDto.newInstance(orderService.searchOrders(supplyingFacility, requestingFacility, program)); } /** * Allows finalizing orders. * * @param orderId The UUID of the order to finalize * @return ResponseEntity with the "#200 OK" HTTP response status on success or ResponseEntity * containing the error description and "#400 Bad Request" status */ @RequestMapping(value = "/orders/{id}/finalize", method = RequestMethod.PUT) public ResponseEntity<OrderDto> finalizeOrder(@PathVariable("id") UUID orderId) throws InvalidOrderStatusException { Order order = orderRepository.findOne(orderId); if (order == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } if (order.getStatus() != ORDERED) { throw new InvalidOrderStatusException(ERROR_ORDER_INVALID_STATUS, ORDERED); } LOGGER.debug("Finalizing the order with id: {}", order); order.setStatus(SHIPPED); orderRepository.save(order); return new ResponseEntity<>(HttpStatus.OK); } /** * Returns csv or pdf of defined object in response. * * @param orderId UUID of order to print * @param format String describing return format (pdf or csv) * @param response HttpServletResponse object */ @RequestMapping(value = "/orders/{id}/print", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public void printOrder(@PathVariable("id") UUID orderId, @RequestParam("format") String format, HttpServletResponse response) throws IOException, OrderFileException { Order order = orderRepository.findOne(orderId); if (order == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Order does not exist."); return; } String[] columns = {"productName", "filledQuantity", "orderedQuantity"}; if ("pdf".equals(format)) { response.setContentType("application/pdf"); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, DISPOSITION_BASE + "order-" + order.getOrderCode() + ".pdf"); orderService.orderToPdf(order, columns, response.getOutputStream()); } else { response.setContentType("text/csv"); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, DISPOSITION_BASE + "order" + order.getOrderCode() + ".csv"); orderService.orderToCsv(order, columns, response.getWriter()); } } /** * Exporting order to csv. * * @param orderId UUID of order to print * @param type export type * @param response HttpServletResponse object */ @RequestMapping(value = "/orders/{id}/export", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public void export( @PathVariable("id") UUID orderId, @RequestParam(value = "type", required = false, defaultValue = "csv") String type, HttpServletResponse response) throws IOException { Order order = orderRepository.findOne(orderId); OrderFileTemplate orderFileTemplate = orderFileTemplateService.getOrderFileTemplate(); if (!"csv".equals(type)) { String msg = "Export type: " + type + " not allowed"; LOGGER.warn(msg); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } if (order == null) { String msg = "Order does not exist."; LOGGER.warn(msg); response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); return; } if (orderFileTemplate == null) { String msg = "Could not export Order, because Order Template File not found"; LOGGER.warn(msg); response.sendError(HttpServletResponse.SC_NOT_FOUND, msg); return; } response.setContentType("text/csv"); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, DISPOSITION_BASE + orderFileTemplate.getFilePrefix() + order.getOrderCode() + ".csv"); try { csvHelper.writeCsvFile(order, orderFileTemplate, response.getWriter()); } catch (IOException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while exporting order to csv."); LOGGER.error("Error occurred while exporting order to csv", ex); } } /** * Manually retry for transferring order file via FTP after updating or checking the FTP * transfer properties. * * @param id UUID of order */ @RequestMapping(value = "/orders/{id}/retry", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public void retryOrderTransfer(@PathVariable("id") UUID id) throws FulfillmentException { Order order = orderRepository.findOne(id); if (null == order) { throw new OrderNotFoundException(id); } permissionService.canTransferOrder(order); if (TRANSFER_FAILED != order.getStatus()) { throw new InvalidOrderStatusException(ERROR_ORDER_RETRY_INVALID_STATUS, TRANSFER_FAILED); } orderService.save(order); } }
package org.petrovic.photos.resources; import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageProcessingException; import com.drew.lang.GeoLocation; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.exif.ExifSubIFDDirectory; import com.drew.metadata.exif.GpsDirectory; import com.google.gson.Gson; import org.imgscalr.Scalr; import org.petrovic.photos.ErrorMessage; import org.petrovic.photos.PhotoMetadata; import org.petrovic.photos.Stream; import org.petrovic.photos.Strings; import javax.imageio.ImageIO; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.List; @Path("/") public class AlbumsResource { private final File albumsDirectory = new File("albums"); private final FilenameFilter fileFilter = new FilenameFilter() { private boolean hasImageExtension(String fileName) { String normalizedFileName = fileName.toLowerCase(); return normalizedFileName.endsWith("jpg") || normalizedFileName.endsWith("png") || normalizedFileName.endsWith("gif"); } private boolean isImageFile(String path) { return hasImageExtension(path) && !path.contains("-thumbnail"); } @Override public boolean accept(File file, String s) { return new File(file, s).isFile() && isImageFile(s); } }; private final FilenameFilter directoryFilter = new FilenameFilter() { @Override public boolean accept(File file, String s) { return new File(file, s).isDirectory(); } }; @GET @Produces(MediaType.TEXT_HTML) public String index() throws IOException { return plainTextFromFile(new File("static/html", "index.html")); } @GET @Produces(MediaType.TEXT_HTML) @Path("/partials/{file: .*html$}") public String html(@PathParam("file") String path) { return plainTextFromFile(new File("static/html/partials", path)); } @GET @Produces("application/javascript") @Path("/{file: .*js$}") public String javascripts(@PathParam("file") String path) { return plainTextFromFile(new File("static", path)); } @GET @Produces("text/css") @Path("/{file: .*css$}") public String css(@PathParam("file") String path) { return plainTextFromFile(new File("static", path)); } @GET @Produces("image/png") @Path("/{file: .*png$}") public StreamingOutput png(@PathParam("file") String path) { return new Stream(new File("static", path)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/albums") public List<String> listAlbums() { String[] list = albumsDirectory.list(directoryFilter); return Arrays.asList(list); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/albums/{albumNumber: [0-9]+}") public List<String> listAlbum(@PathParam("albumNumber") Integer albumNumber) { File albumDirectory = new File(albumsDirectory, albumNumber.toString()); String[] list = albumDirectory.list(fileFilter); return Arrays.asList(list); } @GET @Path("/albums/{albumNumber: [0-9]+}/{imageFile: .*\\.[jJ][pP][gG]$}") @Produces("image/jpeg") public StreamingOutput getImage(@PathParam("albumNumber") Integer albumNumber, @PathParam("imageFile") String imageFileName, @DefaultValue("false") @QueryParam("thumbnail") Boolean useThumbnail) { File albumDirectory = new File(albumsDirectory, albumNumber.toString()); File imageFile; if (useThumbnail) { String fileExtension = Strings.extension(imageFileName); String thumbnailImageFileName = String.format("%s-thumbnail.%s", Strings.nameLessExtension(imageFileName), fileExtension); File thumbnailFile = new File(albumDirectory, thumbnailImageFileName); if (!thumbnailFile.exists()) { createThumbnail(albumDirectory, imageFileName, thumbnailImageFileName); } imageFile = thumbnailFile; } else { imageFile = new File(albumDirectory, imageFileName); } return new Stream(imageFile); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/metadata/{albumNumber: [0-9]+}/{imageFile: .*\\.[jJ][pP][gG]$}") public String photoMetadata(@PathParam("albumNumber") Integer albumNumber, @PathParam("imageFile") String imageFileName) { File t = new File(new File(albumsDirectory, albumNumber.toString()), Strings.nameLessExtension(imageFileName) + ".meta"); return plainTextFromFile(t); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/metadata/{albumNumber: [0-9]+}") public String albumMetadata(@PathParam("albumNumber") Integer albumNumber) { File t = new File(new File(albumsDirectory, albumNumber.toString()), "meta.json"); return plainTextFromFile(t); } @POST @Consumes(MediaType.APPLICATION_OCTET_STREAM) public void addImage() { throw new UnsupportedOperationException(); } private void createThumbnail(File albumDirectory, String imageFileName, String thumbnailImageFileName) { File imageFile = new File(albumDirectory, imageFileName); if (!imageFile.exists()) { throw new WebApplicationException(response(404, String.format("Resource not found: %s", imageFile))); } try { BufferedImage img = ImageIO.read(imageFile); BufferedImage thumbImg = Scalr.resize(img, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, 100, 100, Scalr.OP_ANTIALIAS); File thumbNailImageFile = new File(albumDirectory, thumbnailImageFileName); ImageIO.write(thumbImg, "jpg", thumbNailImageFile); writeExif(imageFile); } catch (IOException e) { throw new WebApplicationException(e, response(500, String.format("Error reading resource: %s", imageFile))); } } private void writeExif(File imageFile) { File metadataFile = new File(imageFile.getParentFile(), Strings.nameLessExtension(imageFile.getName()) + ".meta"); try { PhotoMetadata photoMetadata = null; Metadata metadata = ImageMetadataReader.readMetadata(imageFile); Date date = null; for (Directory directory : metadata.getDirectories()) { if (directory instanceof ExifSubIFDDirectory) { date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL); } if (directory instanceof GpsDirectory) { GpsDirectory gpsDirectory = (GpsDirectory) directory; GeoLocation geoLocation = gpsDirectory.getGeoLocation(); double latitude = geoLocation.getLatitude(); double longitude = geoLocation.getLongitude(); photoMetadata = new PhotoMetadata(date.toString(), latitude, longitude); } } if (photoMetadata == null) { photoMetadata = new PhotoMetadata(date.toString()); } FileWriter fileWriter = new FileWriter(metadataFile); fileWriter.write(new Gson().toJson(photoMetadata)); fileWriter.close(); } catch (ImageProcessingException e) { throw new WebApplicationException(response(404, String.format("Resource not found: %s", imageFile))); } catch (IOException e) { throw new WebApplicationException(e, response(500, String.format("Error reading resource: %s", imageFile))); } } private String plainTextFromFile(File file) { FileReader fileReader; try { fileReader = new FileReader(file); } catch (FileNotFoundException e) { throw new WebApplicationException(response(404, String.format("Resource not found: %s", file))); } BufferedReader br = new BufferedReader(fileReader); String s; StringBuilder sb = new StringBuilder(); try { while ((s = br.readLine()) != null) { sb.append(s); } fileReader.close(); return sb.toString(); } catch (IOException e) { throw new WebApplicationException(response(500, String.format("Error reading resource: %s", file))); } } private Response response(int code, String message) { return Response.status(code).entity(new ErrorMessage(message)).header("Content-type", "application/json").build(); } }
package org.observe.collect.impl; import java.util.Collection; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.function.Function; import org.observe.ObservableValue; import org.observe.Subscription; import org.observe.collect.CollectionSession; import org.observe.collect.ObservableElement; import org.observe.collect.ObservableList; import org.observe.collect.ObservableOrderedElement; import org.observe.util.Transactable; import org.observe.util.Transaction; import prisms.lang.Type; /** * A list whose content can be observed. This list is a classic linked-type list with the following performance characteristics: * <ul> * <li><b>Access by index</b> Linear</li> * <li><b>Addition and removal</b> Constant at the beginning or the end, linear for the middle</li> * </ul> * * @param <E> The type of element in the list */ public class ObservableLinkedList<E> implements ObservableList.PartialListImpl<E> { private final Type theType; private LinkedListInternals theInternals; private LinkedNode theFirst; private LinkedNode theLast; private int theSize; LinkedNode theHighestIndexedFromFirst; LinkedNode theLowestIndexedFromLast; /** * Creates the list * * @param type The type of elements for this list */ public ObservableLinkedList(Type type) { this(type, new ReentrantReadWriteLock(), null, null); } /** * This constructor is for specifying some of the internals of the list. * * @param type The type of elements for this list * @param lock The lock for this list to use * @param session The session for this list to use (see {@link #getSession()}) * @param sessionController The controller for the session. May be null, in which case the transactional methods in this collection will * not actually create transactions. */ public ObservableLinkedList(Type type, ReentrantReadWriteLock lock, ObservableValue<CollectionSession> session, Transactable sessionController) { theType = type; theInternals = new LinkedListInternals(lock, session, sessionController); } @Override public ObservableValue<CollectionSession> getSession() { return theInternals.getSession(); } @Override public Transaction lock(boolean write, Object cause) { return theInternals.lock(write, true, cause); } @Override public Type getType() { return theType; } @Override public Subscription onOrderedElement(Consumer<? super ObservableOrderedElement<E>> onElement) { // Cast is safe because the internals of this set will only create ordered elements return theInternals.onElement((Consumer<ObservableElement<E>>) onElement, true); } @Override public Subscription onElementReverse(Consumer<? super ObservableOrderedElement<E>> onElement) { // Cast is safe because the internals of this set will only create ordered elements return theInternals.onElement((Consumer<ObservableElement<E>>) onElement, false); } private LinkedNode createElement(E value) { return new LinkedNode(value); } @Override public int size() { return theSize; } @Override public E get(int index) { try (Transaction t = theInternals.lock(false, false, null)) { LinkedNode node = theFirst; for(int i = 0; i < index && node != null; i++) node = node.getNext(); if(node == null) throw new IndexOutOfBoundsException(); return node.get(); } } @Override public boolean contains(Object o) { try (Transaction t = theInternals.lock(false, false, null)) { LinkedNode node = theFirst; while(node != null) { if(Objects.equals(node.get(), o)) return true; node = node.getNext(); } } return false; } @Override public Iterator<E> iterator() { return iterate(theFirst, LinkedNode::getNext); } @Override public Iterable<E> descending() { return () -> iterate(theLast, LinkedNode::getPrevious); } private Iterator<E> iterate(LinkedNode node, Function<LinkedNode, LinkedNode> next) { return new Iterator<E>() { private LinkedNode theNext = node; private LinkedNode thePassed; @Override public boolean hasNext() { return theNext != null; } @Override public E next() { thePassed = theNext; theNext = next.apply(theNext); return thePassed.get(); } @Override public void remove() { thePassed.remove(); } }; } @Override public boolean add(E e) { try (Transaction t = theInternals.lock(true, false, null)) { addImpl(e, theLast); } return true; } private LinkedNode addImpl(E value, LinkedNode after) { LinkedNode newNode = createElement(value); newNode.added(after); return newNode; } @Override public void add(int index, E element) { try (Transaction t = theInternals.lock(true, false, null)) { LinkedNode after = index == 0 ? null : getNodeAt(index - 1); addImpl(element, after); } } private LinkedNode getNodeAt(int index) { if(index < 0 || index >= theSize) throw new IndexOutOfBoundsException(index + " of " + theSize); int i; LinkedNode node; Function<LinkedNode, LinkedNode> next; int delta; if(index <= theSize / 2) { i = 0; node = theFirst; next = LinkedNode::getNext; delta = 1; } else { i = theSize - 1; node = theLast; next = LinkedNode::getPrevious; delta = -1; } while(i != index) { node = next.apply(node); i += delta; } return node; } @Override public boolean addAll(Collection<? extends E> c) { if(c.isEmpty()) return false; try (Transaction t = lock(true, null)) { for(E value : c) addImpl(value, theLast); } return true; } @Override public boolean addAll(int index, Collection<? extends E> c) { if(c.isEmpty()) return false; try (Transaction t = lock(true, null)) { LinkedNode after = getNodeAt(index); after = after.getPrevious(); for(E value : c) after = addImpl(value, after); } return true; } @Override public boolean remove(Object o) { try (Transaction t = theInternals.lock(true, false, null)) { LinkedNode node = theFirst; while(node != null && !Objects.equals(node.get(), o)) node = node.getNext(); if(node != null) node.remove(); return node != null; } } @Override public E remove(int index) { try (Transaction t = theInternals.lock(true, false, null)) { LinkedNode node = getNodeAt(index); E ret = node.get(); node.remove(); return ret; } } @Override public boolean removeAll(Collection<?> coll) { boolean ret = false; try (Transaction t = lock(true, null)) { LinkedNode node = theFirst; while(node != null) { if(coll.contains(node.get())) { ret = true; node.remove(); } node = node.getNext(); } } return ret; } @Override public boolean retainAll(Collection<?> coll) { boolean ret = false; try (Transaction t = lock(true, null)) { LinkedNode node = theFirst; while(node != null) { if(!coll.contains(node.get())) { ret = true; node.remove(); } node = node.getNext(); } } return ret; } @Override public void clear() { try (Transaction t = lock(true, null)) { LinkedNode node = theLast; while(node != null) { node.remove(); node = node.getPrevious(); } } } @Override public E set(int index, E element) { try (Transaction t = theInternals.lock(true, false, null)) { LinkedNode node = getNodeAt(index); E ret = node.get(); node.set(element); return ret; } } @Override public ListIterator<E> listIterator(int index) { LinkedNode indexed; try (Transaction t = theInternals.lock(false, false, null)) { indexed = getNodeAt(index); } return new ListIterator<E>() { private LinkedNode theNext = indexed; private boolean isCursorBefore; private boolean hasRemoved = true; @Override public boolean hasNext() { if(theNext == null) return false; if(isCursorBefore && !hasRemoved) return true; else return theNext.getNext() != null; } @Override public E next() { if(!hasNext()) throw new NoSuchElementException(); if(!isCursorBefore || hasRemoved) theNext = theNext.getNext(); E ret = theNext.get(); isCursorBefore = false; hasRemoved = false; return ret; } @Override public boolean hasPrevious() { if(theNext == null) return false; if(!isCursorBefore && !hasRemoved) return true; else return theNext.getPrevious() != null; } @Override public E previous() { if(!hasPrevious()) throw new NoSuchElementException(); if(isCursorBefore || hasRemoved) theNext = theNext.getPrevious(); E ret = theNext.get(); isCursorBefore = true; hasRemoved = false; return ret; } @Override public int nextIndex() { int nextIndex = theNext.getIndex(); if(!isCursorBefore) nextIndex++; return nextIndex; } @Override public int previousIndex() { int prevIndex = theNext.getIndex(); if(isCursorBefore) prevIndex return prevIndex; } @Override public void remove() { if(hasRemoved) throw new IllegalStateException("remove() may only be called (once) after next() or previous()"); hasRemoved = true; try (Transaction t = theInternals.lock(true, false, null)) { theNext.remove(); } } @Override public void set(E e) { if(hasRemoved) throw new IllegalStateException("set() may only be called after next() or previous() and not after remove()"); theNext.set(e); } @Override public void add(E e) { if(hasRemoved) throw new IllegalStateException("add() may only be called after next() or previous() and not after remove()"); try (Transaction t = theInternals.lock(true, false, null)) { addImpl(e, theNext); } } }; } @Override public String toString() { return ObservableList.toString(this); } private class LinkedNode extends InternalObservableElementImpl<E> { private LinkedNode thePrevious; private LinkedNode theNext; private int theIndexFromFirst; private int theIndexFromLast; private boolean isRemoved; public LinkedNode(E value) { super(ObservableLinkedList.this.getType(), value); } LinkedNode getPrevious() { return thePrevious; } LinkedNode getNext() { return theNext; } int getIndex() { if(isRemoved) return theIndexFromFirst; if(theIndexFromFirst < theHighestIndexedFromFirst.theIndexFromFirst || this == theHighestIndexedFromFirst) return theIndexFromFirst; else if(theIndexFromLast < theLowestIndexedFromLast.theIndexFromLast || this == theLowestIndexedFromLast) return theSize - theIndexFromLast - 1; // Don't know our index. Find it. return cacheIndex(); } private int cacheIndex() { int lowDiff = theIndexFromFirst - theHighestIndexedFromFirst.theIndexFromFirst; int highDiff = theIndexFromLast - theLowestIndexedFromLast.theIndexFromLast; while(true) { // This loop *should* be safe, since we know we're an element in the collection and we're between the highest and lowest // indexed elements. If this assumption does not hold (due to implementation errors in this list), this loop will just // generate an NPE if(lowDiff < highDiff) { theHighestIndexedFromFirst.theNext.theIndexFromFirst = theHighestIndexedFromFirst.theIndexFromFirst + 1; theHighestIndexedFromFirst = theHighestIndexedFromFirst.theNext; if(this == theHighestIndexedFromFirst) return theIndexFromFirst; lowDiff++; } else { theLowestIndexedFromLast.thePrevious.theIndexFromLast = theLowestIndexedFromLast.theIndexFromLast + 1; theLowestIndexedFromLast = theLowestIndexedFromLast.thePrevious; if(this == theLowestIndexedFromLast) return theIndexFromLast; highDiff++; } } } void added(LinkedNode after) { thePrevious = after; if(theLast == after) theLast = this; if(after == null) { theNext = theFirst; theFirst = this; } else { theNext = after.getNext(); after.theNext = this; } theSize++; // Maintain cached indexes where possible if(after != null) { // For starters, assume we know where after is in relation to first and last. Adjust indexes accordingly. theIndexFromFirst = after.theIndexFromFirst + 1; theIndexFromLast = after.theIndexFromLast; after.theIndexFromLast++; if(theHighestIndexedFromFirst == after) theHighestIndexedFromFirst = this; else if(theIndexFromFirst < theHighestIndexedFromFirst.theIndexFromFirst) theHighestIndexedFromFirst = this; if(after.theIndexFromLast < theLowestIndexedFromLast.theIndexFromLast) theLowestIndexedFromLast = after; } else { // Inserting at beginning theIndexFromFirst = 0; theIndexFromLast = theSize - 1; theHighestIndexedFromFirst = this; if(theLowestIndexedFromLast == theNext) theLowestIndexedFromLast = this; } theInternals.fireNewElement(this); } @Override void remove() { if(thePrevious != null) thePrevious.theNext = theNext; if(theNext != null) theNext.thePrevious = thePrevious; if(this == theFirst) theFirst = theNext; if(this == theLast) theLast = thePrevious; theSize theIndexFromFirst = theIndexFromLast = getIndex(); isRemoved = true; // Maintain cached indexes where possible if(theIndexFromFirst <= theHighestIndexedFromFirst.theIndexFromFirst) { if(thePrevious != null) theHighestIndexedFromFirst = thePrevious; else theHighestIndexedFromFirst = theNext; } if(theIndexFromLast <= theLowestIndexedFromLast.theIndexFromLast) { if(theNext != null) theLowestIndexedFromLast = theNext; else theLowestIndexedFromLast = thePrevious; } super.remove(); } } private class LinkedListInternals extends DefaultCollectionInternals<E> { public LinkedListInternals(ReentrantReadWriteLock lock, ObservableValue<CollectionSession> session, Transactable sessionController) { super(lock, session, sessionController, null, null); } @Override Iterable<? extends InternalObservableElementImpl<E>> getElements(boolean forward) { return new Iterable<LinkedNode>() { @Override public Iterator<LinkedNode> iterator() { return new Iterator<LinkedNode>() { private LinkedNode next = forward ? theFirst : theLast; @Override public boolean hasNext() { return next != null; } @Override public LinkedNode next() { LinkedNode ret = next; next = forward ? next.getNext() : next.getPrevious(); return ret; } }; } }; } @Override ObservableElement<E> createExposedElement(InternalObservableElementImpl<E> internal, Collection<Subscription> subscriptions) { LinkedNode orderedInternal = (LinkedNode) internal; class ExposedOrderedObservableElement extends ExposedObservableElement<E> implements ObservableOrderedElement<E> { ExposedOrderedObservableElement() { super(internal, subscriptions); } @Override public int getIndex() { return orderedInternal.getIndex(); } @Override public String toString() { return getType() + " list[" + getIndex() + "]=" + get(); } } return new ExposedOrderedObservableElement(); } } }
package org.wikimedia.cassandra.metrics; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.management.JMX; import javax.management.MBeanServerConnection; import javax.management.MalformedObjectNameException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Sets; import com.yammer.metrics.reporting.JmxReporter; public class JmxCollector implements AutoCloseable { private static final String DEFAULT_HOST = "localhost"; private static final int DEFAULT_PORT = 7199; private static final String DEFAULT_PREFIX = "cassandra"; private static final String FORMAT_URL = "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"; private static final Map<String, Class<?>> mbeanClasses; private static final Set<ObjectName> blacklist; static { mbeanClasses = new HashMap<String, Class<?>>(); mbeanClasses.put("com.yammer.metrics.reporting.JmxReporter$Gauge", JmxReporter.GaugeMBean.class); mbeanClasses.put("com.yammer.metrics.reporting.JmxReporter$Timer", JmxReporter.TimerMBean.class); mbeanClasses.put("com.yammer.metrics.reporting.JmxReporter$Counter", JmxReporter.CounterMBean.class); mbeanClasses.put("com.yammer.metrics.reporting.JmxReporter$Meter", JmxReporter.MeterMBean.class); mbeanClasses.put("com.yammer.metrics.reporting.JmxReporter$Histogram", JmxReporter.HistogramMBean.class); blacklist = new HashSet<ObjectName>(); try { blacklist.add(new ObjectName("org.apache.cassandra.metrics:type=ColumnFamily,name=SnapshotsSize")); blacklist .add(new ObjectName( "org.apache.cassandra.metrics:type=ColumnFamily,keyspace=system,scope=compactions_in_progress,name=SnapshotsSize")); } catch (MalformedObjectNameException e) { e.printStackTrace(); /* FIXME: handle this. */ } } private final String hostname; private final int port; private final String prefix; private final JMXConnector jmxc; private final MBeanServerConnection mbeanServerConn; private final ObjectName metricsObjectName; public JmxCollector() throws IOException { this(DEFAULT_HOST, DEFAULT_PORT, DEFAULT_PREFIX); } public JmxCollector(String host, int port, String prefix) throws IOException { this.hostname = checkNotNull(host, "host argument"); this.port = checkNotNull(port, "port argument"); this.prefix = checkNotNull(prefix, "prefix argument"); try { this.metricsObjectName = new ObjectName("org.apache.cassandra.metrics:*"); } catch (MalformedObjectNameException e1) { throw new RuntimeException("a bug!"); } JMXServiceURL jmxUrl; try { jmxUrl = new JMXServiceURL(String.format(FORMAT_URL, this.hostname, this.port)); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); } /* FIXME: add authentication support */ Map<String, Object> env = new HashMap<String, Object>(); this.jmxc = JMXConnectorFactory.connect(jmxUrl, env); this.mbeanServerConn = jmxc.getMBeanServerConnection(); } public void getSamples(SampleVisitor visitor) throws IOException { for (ObjectInstance instance : getConnection().queryMBeans(this.metricsObjectName, null)) { if (!interesting(instance.getObjectName())) continue; Joiner joiner = Joiner.on("."); Object proxy = getMBeanProxy(instance); String name = graphiteName(instance.getObjectName()); int timestamp = (int) (System.currentTimeMillis() / 1000); if (proxy instanceof JmxReporter.TimerMBean) { visitor.visit(new Sample(joiner.join(name, "50percentile"), ((JmxReporter.TimerMBean) proxy).get50thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "75percentile"), ((JmxReporter.TimerMBean) proxy).get75thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "95percentile"), ((JmxReporter.TimerMBean) proxy).get95thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "98percentile"), ((JmxReporter.TimerMBean) proxy).get98thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "99percentile"), ((JmxReporter.TimerMBean) proxy).get99thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "999percentile"), ((JmxReporter.TimerMBean) proxy).get999thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "1MinuteRate"), ((JmxReporter.TimerMBean) proxy).getOneMinuteRate(), timestamp)); visitor.visit(new Sample(joiner.join(name, "5MinuteRate"), ((JmxReporter.TimerMBean) proxy).getFiveMinuteRate(), timestamp)); visitor.visit(new Sample(joiner.join(name, "15MinuteRate"), ((JmxReporter.TimerMBean) proxy).getFifteenMinuteRate(), timestamp)); visitor.visit(new Sample(joiner.join(name, "count"), ((JmxReporter.TimerMBean) proxy).getCount(), timestamp)); visitor.visit(new Sample(joiner.join(name, "max"), ((JmxReporter.TimerMBean) proxy).getMax(), timestamp)); visitor.visit(new Sample(joiner.join(name, "mean"), ((JmxReporter.TimerMBean) proxy).getMean(), timestamp)); visitor.visit(new Sample(joiner.join(name, "meanRate"), ((JmxReporter.TimerMBean) proxy).getMeanRate(), timestamp)); visitor.visit(new Sample(joiner.join(name, "min"), ((JmxReporter.TimerMBean) proxy).getMin(), timestamp)); visitor.visit(new Sample(joiner.join(name, "stddev"), ((JmxReporter.TimerMBean) proxy).getStdDev(), timestamp)); continue; } if (proxy instanceof JmxReporter.HistogramMBean) { visitor.visit(new Sample(joiner.join(name, "50percentile"), ((JmxReporter.HistogramMBean) proxy).get50thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "75percentile"), ((JmxReporter.HistogramMBean) proxy).get75thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "95percentile"), ((JmxReporter.HistogramMBean) proxy).get95thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "98percentile"), ((JmxReporter.HistogramMBean) proxy).get98thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "99percentile"), ((JmxReporter.HistogramMBean) proxy).get99thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "999percentile"), ((JmxReporter.HistogramMBean) proxy).get999thPercentile(), timestamp)); visitor.visit(new Sample(joiner.join(name, "max"), ((JmxReporter.HistogramMBean) proxy).getMax(), timestamp)); visitor.visit(new Sample(joiner.join(name, "mean"), ((JmxReporter.HistogramMBean) proxy).getMean(), timestamp)); visitor.visit(new Sample(joiner.join(name, "min"), ((JmxReporter.HistogramMBean) proxy).getMin(), timestamp)); visitor.visit(new Sample(joiner.join(name, "stddev"), ((JmxReporter.HistogramMBean) proxy).getStdDev(), timestamp)); continue; } if (proxy instanceof JmxReporter.GaugeMBean) { visitor.visit(new Sample(joiner.join(name, "value"), ((JmxReporter.GaugeMBean) proxy).getValue(), timestamp)); continue; } if (proxy instanceof JmxReporter.CounterMBean) { visitor.visit(new Sample(joiner.join(name, "count"), ((JmxReporter.CounterMBean) proxy).getCount(), timestamp)); continue; } } } @Override public void close() throws IOException { this.jmxc.close(); } MBeanServerConnection getConnection() { return this.mbeanServerConn; } Object getMBeanProxy(ObjectInstance instance) { return JMX.newMBeanProxy(getConnection(), instance.getObjectName(), mbeanClasses.get(instance.getClassName())); } String graphiteName(ObjectName name) { StringBuilder builder = new StringBuilder(this.prefix).append('.').append(name.getDomain()); // Ideally we'd use getKeyPropertyList here, but that returns a map that // obscures the original ordering (which I assume/hope is stable), so // we're forced to parse it ourselves here. /* FIXME: you can actually hear this suck. */ String propertiesString = name.getKeyPropertyListString(); if (propertiesString.contains("type=ColumnFamily")) { if (name.getKeyProperty("keyspace") == null) propertiesString = propertiesString.replaceFirst("type=ColumnFamily", "type=ColumnFamily,keyspace=all"); } for (String property : Splitter.on(",").trimResults().split(propertiesString)) { List<String> kv = Splitter.on("=").trimResults().limit(2).splitToList(property); builder.append('.').append(kv.get(1)); } return builder.toString(); } /* TODO: Ideally, the "interesting" criteria should be configurable. */ private static Set<String> interestingTypes = Sets.newHashSet( "Cache", "ClientRequest", "ColumnFamily", "Connection", "CQL", "DroppedMessage", "FileCache", "IndexColumnFamily", "Storage", "ThreadPools", "Compaction", "ReadRepair", "CommitLog"); /* XXX: This is a hot mess. */ private boolean interesting(ObjectName objName) { if (blacklist.contains(objName)) return false; /* XXX: These metrics are gauges that return long[]; Pass for now... */ String name = objName.getKeyProperty("name"); if (name != null && (name.equals("EstimatedRowSizeHistogram") || name.equals("EstimatedColumnCountHistogram"))) { return false; } String type = objName.getKeyProperty("type"); if (type != null && interestingTypes.contains(type)) { String keyspace = objName.getKeyProperty("keyspace"); if (keyspace == null || !keyspace.startsWith("system")) return true; } return false; } public static void main(String... args) throws IOException, Exception { try (JmxCollector collector = new JmxCollector("localhost", 7100, "cassandra")) { SampleVisitor visitor = new SampleVisitor() { @Override public void visit(Sample sample) { System.out.printf("%s=%s%n", sample.getName(), sample.getValue()); } }; collector.getSamples(visitor); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.oneandone.idev.johanna.store; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author kiesel */ public class SessionStore { private static final Logger LOG = Logger.getLogger(SessionStore.class.getName()); private Map<String,Session> store; private int intervalGC= 60000; private Timer gc; public SessionStore() { this.store = new ConcurrentHashMap<String, Session>(); } public int size() { return this.store.size(); } public Session createSession(int ttl) { return this.createSession("", ttl); } public Session createSession(String prefix, int ttl) { return this.createSession(this.newIdentifier(prefix), ttl); } public Session createSession(Identifier id, int ttl) { Session s= new Session(id, ttl); this.store.put(s.getId(), s); return s; } protected Identifier newIdentifier(String prefix) { return new MD5Identifier(prefix); } protected Session session(String id) { Session s= this.store.get(id); // Protect against delivery of expired sessions if (s != null) { if (s.hasExpired()) return null; } return s; } public boolean hasSession(String id) { return this.session(id) != null; } public boolean terminateSession(String id) { Session s= this.session(id); if (null == s) { return false; } return this.terminateSession(s); } private boolean terminateSession(Session s) { s.expire(); return true; } public Session getSession(String id) { return this.session(id); } public void cleanupSessions() { this.dumpStats(); LOG.info("Starting session garbage collection run..."); Iterator<String> i= this.store.keySet().iterator(); int checked= 0, cleaned= 0; while (i.hasNext()) { Session s= this.store.get(i.next()); checked++; if (s.terminateIfExpired()) { i.remove(); cleaned++; } } LOG.info("Session garbage collection completed."); LOG.log(Level.INFO, "Checked [{0}] / cleaned [{1}]", new Object[]{checked, cleaned}); } public void dumpStats() { long memory= 0; long count= 0; long terminated= 0; Iterator<String> i= this.store.keySet().iterator(); while (i.hasNext()) { Session s= this.store.get(i.next()); count++; memory+= s.payloadBytesUsed(); if (s.hasExpired()) terminated++; } LOG.log(Level.INFO, "Stats: [{0}] sessions [{1}] expired, [{2}] bytes used", new Object[]{count, terminated, memory}); } public void startAutomaticGarbageCollectionThread() { if (null != this.gc) return; LOG.info("---> Scheduled garbage collection run."); this.gc= new Timer("SessionStoreGC", true); this.gc.schedule(new TimerTask() { @Override public void run() { cleanupSessions(); } }, intervalGC, intervalGC); } public void stopAutomaticGarbageCollection() throws InterruptedException { if (this.gc == null) return; LOG.info("---> Unscheduling garbage collection run."); this.gc.cancel(); } }
package pixlepix.auracascade.network; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import pixlepix.auracascade.AuraCascade; import pixlepix.auracascade.item.ItemAngelJump; import pixlepix.auracascade.main.event.EventHandler; public class PacketAngelJump implements IMessage { public EntityPlayer entityPlayer; public boolean up; public PacketAngelJump(EntityPlayer player, boolean up) { this.entityPlayer = player; this.up = up; } public PacketAngelJump() { } @Override public void fromBytes(ByteBuf buf) { World world = DimensionManager.getWorld(buf.readInt()); if (world != null) { entityPlayer = (EntityPlayer) world.getEntityByID(buf.readInt()); } up = buf.readBoolean(); } @Override public void toBytes(ByteBuf buf) { buf.writeInt(entityPlayer.worldObj.provider.dimensionId); buf.writeInt(entityPlayer.getEntityId()); buf.writeBoolean(up); } public static class PacketAngelJumpHandler implements IMessageHandler<PacketAngelJump, IMessage> { @Override public IMessage onMessage(PacketAngelJump msg, MessageContext ctx) { if (msg.entityPlayer != null) { EntityPlayer player = msg.entityPlayer; if (EventHandler.getBaubleFromInv(ItemAngelJump.class, player) != null) { for (int y = (int) (player.posY + (msg.up ? 2 : -2)); y < 255 && y > -1; y += msg.up ? 1 : -1) { if (!player.worldObj.isAirBlock((int) Math.floor(player.posX), y, (int) Math.floor(player.posZ)) && player.worldObj.isAirBlock((int) Math.floor(player.posX), y + 1, (int) Math.floor(player.posZ)) && player.worldObj.isAirBlock((int) Math.floor(player.posX), y + 2, (int) Math.floor(player.posZ))) { player.setPositionAndUpdate(player.posX, y + 2, player.posZ); AuraCascade.proxy.networkWrapper.sendToAllAround(new PacketBurst(8, player.posX, player.posY - 0.5, player.posZ), new NetworkRegistry.TargetPoint(player.worldObj.provider.dimensionId, player.posX, player.posY, player.posZ, 32)); break; } } } } return null; } } }
package pl.domzal.junit.docker.rule; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.spotify.docker.client.messages.PortBinding; public class DockerRuleBuiler { private static final int WAIT_FOR_DEFAULT_SECONDS = 30; private String imageName; private List<String> binds = new ArrayList<>(); private List<String> env = new ArrayList<>(); private ExposePortBindingBuilder exposeBuilder = ExposePortBindingBuilder.builder(); private boolean publishAllPorts = true; private String[] cmd; private String[] extraHosts; private String waitForMessage; private int waitForMessageSeconds = WAIT_FOR_DEFAULT_SECONDS; private boolean keepContainer = false; private boolean imageAlwaysPull = false; private PrintStream stdoutWriter; private PrintStream stderrWriter; DockerRuleBuiler(){} public DockerRule build() { return new DockerRule(this); } private static String[] nullToEmpty(String[] value) { return value==null ? new String[0] : value; } /** * Command to execute on container. */ public DockerRuleBuiler cmd(String... cmd) { this.cmd = cmd; return this; } String[] cmd() { return nullToEmpty(cmd); } /** * Image name to be used (required). */ public DockerRuleBuiler imageName(String imageName) { this.imageName = imageName; return this; } String imageName() { if (StringUtils.isEmpty(imageName)) { throw new IllegalStateException("imageName cannot be empty"); } return imageName; } /** * Add extra host definitions into containers <code>/etc/hosts</code>. * @param extraHosts List of host matching format "hostname:address" (like desribed for 'docker run --add-host'). */ public DockerRuleBuiler extraHosts(String... extraHosts) { this.extraHosts = extraHosts; return this; } String[] extraHosts() { return nullToEmpty(extraHosts); } /** * Make rule to wait for specified text in log on container start. * * @param waitForMessage Message to wait for. */ public DockerRuleBuiler waitForMessage(String waitForMessage) { this.waitForMessage = waitForMessage; return this; } /** * Make rule to wait for specified text in log on container start. * * @param waitForMessage Message to wait for. * @param waitSeconds Number of seconds to wait. Rule startup will fail on timeout. */ public DockerRuleBuiler waitForMessage(String waitForMessage, int waitSeconds) { this.waitForMessage = waitForMessage; this.waitForMessageSeconds = waitSeconds; return this; } String waitForMessage() { return waitForMessage; } int waitForMessageSeconds() { return waitForMessageSeconds; } /** * Keep stopped container after test. */ public DockerRuleBuiler keepContainer(boolean keepContainer) { this.keepContainer = keepContainer; return this; } boolean keepContainer() { return keepContainer; } /** * Force image pull even when image is already present. */ public DockerRuleBuiler imageAlwaysPull(boolean alwaysPull) { this.imageAlwaysPull = alwaysPull; return this; } boolean imageAlwaysPull() { return imageAlwaysPull; } /** * Host directory to be mounted into container.<br/> * Please note that in boot2docker environments (OSX or Windows) * only locations inside $HOME can work (/Users or /c/Users respectively).<br/> * On Windows it is safer to use {@link #mountFrom(File)} instead. * * @param hostPath Directory to be mounted - must be specified Unix style. */ public DockerRuleMountBuilderTo mountFrom(String hostPath) throws InvalidVolumeFrom { return new DockerRuleMountBuilder(this, hostPath); } /** * Host directory to be mounted into container.<br/> * Please note that in boot2docker environments (OSX or Windows) * only locations inside $HOME can work (/Users or /c/Users respectively). * * @param hostDir Directory to be mounted. */ public DockerRuleMountBuilderTo mountFrom(File hostDir) throws InvalidVolumeFrom { String hostDirUnixPath = DockerRuleMountBuilder.toUnixStylePath(hostDir.getAbsolutePath()); return new DockerRuleMountBuilder(this, hostDirUnixPath); } DockerRuleBuiler addBind(String bindString) { binds.add(bindString); return this; } List<String> binds() { return binds; } /** * Set environment variable in the container. */ public DockerRuleBuiler env(String envName, String envValue) { env.add(String.format("%s=%s", envName, envValue)); return this; } List<String> env() { return Collections.unmodifiableList(env); } /** * Expose container port to specified host port. By default * all container port are exposed to randomly assigned free * host ports. <b>Using manual expose disables this so user must * expose all required ports by hand</b>. * TODO automatic exposure is disabled after single manual exposure * * @param hostPort Host port internal port will be mapped to. * @param containerPort Container port to map to host. */ public DockerRuleBuiler expose(String hostPort, String containerPort) { publishAllPorts = false; exposeBuilder.expose(hostPort, containerPort); return this; } Map<String, List<PortBinding>> exposePortBindings() { return Collections.unmodifiableMap(exposeBuilder.build()); } /** * Redefine {@link PrintStream} STDOUT goes to. */ public DockerRuleBuiler stdoutWriter(PrintStream stdoutWriter) { this.stdoutWriter = stdoutWriter; return this; } PrintStream stdoutWriter() { return stdoutWriter; } /** * Redefine {@link PrintStream} STDERR goes to. */ public DockerRuleBuiler stderrWriter(PrintStream stderrWriter) { this.stderrWriter = stderrWriter; return this; } PrintStream stderrWriter() { return stderrWriter; } /** * Enable / disable publishing all container ports to dynamically * allocated host ports. Publishing is enabled by default. * Dynamic port container ports was mapped to can be read after start * with {@link DockerRule#getExposedContainerPort(String)}. * * @param publishAllPorts true if you want all container ports to be published by default. */ public DockerRuleBuiler publishAllPorts(boolean publishAllPorts) { this.publishAllPorts = publishAllPorts; return this; } boolean publishAllPorts() { return publishAllPorts; } }
package org.powertac.visualizer.web.rest; import com.codahale.metrics.annotation.Timed; import org.apache.commons.io.FileExistsException; import org.apache.commons.io.IOUtils; import org.powertac.visualizer.domain.File; import org.powertac.visualizer.domain.Game; import org.powertac.visualizer.domain.User; import org.powertac.visualizer.domain.enumeration.FileType; import org.powertac.visualizer.repository.UserRepository; import org.powertac.visualizer.security.SecurityUtils; import org.powertac.visualizer.service.FileService; import org.powertac.visualizer.service.GameService; import org.powertac.visualizer.service_ptac.SyncFilesService; import org.powertac.visualizer.web.rest.util.HeaderUtil; import org.powertac.visualizer.web.rest.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing File. */ @RestController @RequestMapping("/api") public class FileResource { private final Logger log = LoggerFactory.getLogger(FileResource.class); private static final String ENTITY_NAME = "file"; private final FileService fileService; private final GameService gameService; private final UserRepository userRepository; public FileResource(FileService fileService, GameService gameService, UserRepository userRepository) { this.fileService = fileService; this.gameService = gameService; this.userRepository = userRepository; } @Autowired private SyncFilesService syncFilesService; /** * POST /files : Create a new file. * * @param file the file to create * @return the ResponseEntity with status 201 (Created) and with body the new file, or with status 400 (Bad Request) if the file has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/files") @Timed public ResponseEntity<File> createFile(@Valid @RequestBody File file) throws URISyntaxException { log.debug("REST request to save File : {}", file); if (file.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new file cannot already have an ID")).body(null); } String login = SecurityUtils.getCurrentUserLogin(); User user = userRepository.findOneByLogin(login).orElse(null); file.setOwner(user); File result = fileService.save(file); return ResponseEntity.created(new URI("/api/files/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /files : Updates an existing file. * * @param file the file to update * @return the ResponseEntity with status 200 (OK) and with body the updated file, * or with status 400 (Bad Request) if the file is not valid, * or with status 500 (Internal Server Error) if the file couldnt be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/files") @Timed public ResponseEntity<File> updateFile(@Valid @RequestBody File file) throws URISyntaxException { log.debug("REST request to update File : {}", file); if (file.getId() == null) { return createFile(file); } File result = fileService.save(file); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, file.getId().toString())) .body(result); } /** * GET /files : get all the files. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of files in body * @throws URISyntaxException if there is an error to generate the pagination HTTP headers */ @GetMapping("/files") @Timed public ResponseEntity<List<File>> getAllFiles(Pageable pageable) throws URISyntaxException { log.debug("REST request to get a page of Files"); Page<File> page = fileService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/files"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /files/:id : get the "id" file. * * @param id the id of the file to retrieve * @return the ResponseEntity with status 200 (OK) and with body the file, or with status 404 (Not Found) */ @GetMapping("/files/{id}") @Timed public ResponseEntity<File> getFile(@PathVariable Long id) { log.debug("REST request to get File : {}", id); File file = fileService.findOne(id); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(file)); } /** * DELETE /files/:id : delete the "id" file. * * @param id the id of the file to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/files/{id}") @Timed public ResponseEntity<Void> deleteFile(@PathVariable Long id) { log.debug("REST request to delete File : {}", id); File file = fileService.findOne(id); fileService.delete(id); file.getType().getFile(file.getOwner(), file.getName()).delete(); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } /** * Get all files owned by logged in user, plus all shared files. */ @GetMapping("/myfiles/{type}/") @Timed public ResponseEntity<List<File>> getMyFiles( @Valid @NotNull @PathVariable String type) throws URISyntaxException { syncFilesService.syncFileSystem(); FileType fileType = FileType.valueOf(type.toUpperCase()); log.debug("REST request to get owned and shared files, type = " + type); String login = SecurityUtils.getCurrentUserLogin(); List<File> list = fileService.findByOwnerIsCurrentUserOrShared(login, fileType); return new ResponseEntity<>(list, HttpStatus.OK); } /** * Download a file. * TODO document. * * @param type * @param id * @param response * @throws IOException */ @GetMapping("/myfiles/{type}/{id}") @Timed public void getMyFile (@Valid @NotNull @PathVariable String type, @Valid @NotNull @PathVariable Long id, HttpServletResponse response) throws IOException { log.debug("REST request to download a file"); FileType fileType = FileType.valueOf(type.toUpperCase()); if (fileType == null) { throw new IllegalArgumentException("Unknown type " + type); } File file = fileService.findOne(id); java.io.File raw = fileType.getFile(file.getOwner(), file.getName()); try ( InputStream in = new BufferedInputStream(new FileInputStream(raw)); OutputStream out = new BufferedOutputStream(response.getOutputStream()) ) { response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); response.setHeader("Content-Type", fileType.getContentType()); IOUtils.copy(in, out); } } /** * Upload a file. * TODO document. * * @param part * @param type * @param shared * @throws FileExistsException * @throws IOException * @throws URISyntaxException */ @PostMapping("/myfiles/{type}/") @Timed public ResponseEntity<File> postFile (@Valid @NotNull @PathVariable String type, @RequestParam("shared") Boolean shared, @RequestParam("overwrite") Boolean overwrite, @Valid @NotNull @RequestParam("file") MultipartFile part) throws IOException, URISyntaxException { String name = part.getOriginalFilename(); log.debug("REST request to upload a " + type.toString() + " file: " + name + " @ " + part.getSize() + " bytes."); String login = SecurityUtils.getCurrentUserLogin(); User user = userRepository.findOneByLogin(login).orElse(null); FileType fileType = FileType.valueOf(type.toUpperCase()); java.io.File raw = fileType.getFile(user, name); if (raw.exists()) { if (overwrite) { List<File> files = fileService.findByOwnerIsCurrentUser(login, fileType); for (File file: files) { if (file.getName().equals(name)) { for (Game game : gameService.findByAssociatedFile(file)) { switch(fileType) { case BOOT: game.setBootFile(null); break; case CONFIG: game.setConfigFile(null); break; case SEED: game.setSeedFile(null); break; case WEATHER: game.setWeatherFile(null); break; case STATE: game.setStateFile(null); break; case TRACE: game.setTraceFile(null); break; default: throw new IllegalArgumentException("Can't overwrite " + type + " file"); } gameService.save(game); } fileService.delete(file.getId()); break; } } } else { throw new FileExistsException(); } } try ( OutputStream out = new FileOutputStream(raw); InputStream in = part.getInputStream() ) { byte[] buf = new byte[65536]; while (true) { int len = in.read(buf); if (len > 0) { out.write(buf, 0, len); } else { break; } } File file = new File(); file.setType(fileType); file.setName(name); file.setOwner(user); file.setShared(shared); file = fileService.save(file); return ResponseEntity.created(new URI("/api/files/" + file.getId())) .headers(HeaderUtil.createEntityCreationAlert("file", file.getId().toString())) .body(file); } } }
package rapture.plugin; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.security.NoSuchAlgorithmException; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.google.common.collect.Maps; import rapture.common.PluginConfig; import rapture.common.PluginTransportItem; import rapture.common.RaptureURI; import rapture.common.Scheme; import rapture.common.WorkOrderExecutionState; import rapture.common.client.HttpDecisionApi; import rapture.common.client.HttpDocApi; import rapture.common.client.HttpIndexApi; import rapture.common.client.HttpPluginApi; import rapture.common.exception.ExceptionToString; import rapture.common.exception.RaptureExceptionFactory; import rapture.common.impl.jackson.JacksonUtil; import rapture.helper.IntegrationTestHelper; import rapture.plugin.install.PluginContentReader; import rapture.plugin.install.PluginSandbox; import rapture.plugin.install.PluginSandboxItem; public class PluginApiTest { HttpPluginApi pluginApi=null; Set <String> installedSet = null; IntegrationTestHelper helper=null; @BeforeClass(groups={"plugin","nightly"}) @Parameters({"RaptureURL","RaptureUser","RapturePassword"}) public void setUp(@Optional("http://localhost:8665/rapture")String url, @Optional("rapture")String username, @Optional("rapture")String password ) { helper = new IntegrationTestHelper(url, username, password); pluginApi = helper.getPluginApi(); installedSet = new HashSet<String> (); } @Test(groups={"plugin","nightly"},dataProvider="pluginZips") public void testInstallAndUninstallPlugin (String pluginName,String zipFileName,String description) { Reporter.log("Testing plugin: " + pluginName,true); //import the zip configuration String zipAbsFilePath = System.getProperty("user.dir")+ File.separator+"build"+File.separator+"resources"+File.separator+"test"+File.separator+"plugin"+File.separator+"nightly"+File.separator+zipFileName; Reporter.log("Reading in file from "+zipAbsFilePath,true); ZipFile orgZipFile = null; try { orgZipFile= new ZipFile(zipAbsFilePath); Assert.assertNotNull(orgZipFile, pluginName); } catch (Exception e) { Reporter.log("Got error reading zip file " + zipAbsFilePath, true); Reporter.log(ExceptionToString.format(e), true); Assert.fail("Got error reading zip file " + zipAbsFilePath); } PluginConfig pluginConfig = getPluginConfigFromZip(zipAbsFilePath); Assert.assertNotNull(pluginConfig, pluginName); //check plugin zip configuration Assert.assertEquals(pluginConfig.getPlugin(),pluginName); Assert.assertEquals(pluginConfig.getDescription(),description); //import (to memory) using plugin sandbox PluginSandbox sandbox = new PluginSandbox(); sandbox.setConfig(pluginConfig); sandbox.setStrict(false); String rootDir = File.separator + "tmp" + File.separator+ "plugin1_" + System.currentTimeMillis(); Reporter.log("Test for " + zipFileName + ". Dir is " + rootDir,true); //add the individual items to sandbox sandbox.setRootDir(new File(rootDir, pluginConfig.getPlugin())); Enumeration<? extends ZipEntry> entries = orgZipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } try { sandbox.makeItemFromZipEntry(orgZipFile, entry); } catch (Exception e) { Reporter.log("Error making sandbox item",true); } } Assert.assertEquals(sandbox.getPluginName(),pluginName); Assert.assertEquals(sandbox.getDescription(),pluginConfig.getDescription()); //get ready to install plugin Map<String, PluginTransportItem> payload = Maps.newHashMap(); Set <String> itemSet=new HashSet<String>(); for (PluginSandboxItem item : sandbox.getItems(null)) { try { PluginTransportItem payloadItem = item.makeTransportItem(); payload.put(item.getURI().toString(), payloadItem); itemSet.add(item.getURI().toString().contains("$")?item.getURI().toString().substring(0, item.getURI().toString().indexOf("$")-1) :item.getURI().toString()); } catch (Exception ex) { Reporter.log("Exception creating plugin " +ex.getMessage(),true); } } //install the plugin using the http api pluginApi.installPlugin(sandbox.makeManifest(null), payload); installedSet.add(pluginName); PluginConfig thePlugin=null; for (PluginConfig c :pluginApi.getInstalledPlugins()) if (c.getPlugin().compareTo(pluginName) ==0) thePlugin=c; Assert.assertEquals (thePlugin.getPlugin(),pluginName,"Plugin "+pluginName+" has unexpected name."); Assert.assertEquals (thePlugin.getDescription(),description,"Plugin "+pluginName+" has unexpected description."); Assert.assertEquals(pluginApi.verifyPlugin(pluginName).keySet(),itemSet,"Problem with installed items"); pluginApi.uninstallPlugin(pluginName); boolean installed=false; for (PluginConfig c :pluginApi.getInstalledPlugins()) if (c.getPlugin().compareTo(pluginName) ==0) installed=true; Assert.assertFalse(installed,"Plugin "+pluginName + " expected to be uninstalled"); installedSet.remove(pluginName); } @Test(groups={"plugin","nightly"}, dataProvider="workflowPluginZips",description="install a plugin and run work order") public void testPluginWithWorkorder(String zipFileName, String pluginName, String expectedDescription, String workflowUri, String ctxString) throws IOException, NoSuchAlgorithmException, InterruptedException, SecurityException, NoSuchMethodException{ Reporter.log("Testing plugin: " + pluginName,true); //import the zip configuration String zipAbsFilePath = System.getProperty("user.dir")+ File.separator+"build"+File.separator+"resources"+File.separator+"test"+File.separator+"plugin"+File.separator+"nightly"+File.separator+zipFileName; Reporter.log("Reading in file from "+zipAbsFilePath,true); ZipFile orgZipFile = new ZipFile(zipAbsFilePath); PluginConfig pluginConfig = getPluginConfigFromZip(zipAbsFilePath); //check plugin zip configuration Assert.assertNotNull(pluginConfig, pluginName); Assert.assertEquals(pluginConfig.getPlugin(),pluginName); Assert.assertEquals(pluginConfig.getDescription(),expectedDescription); //import (to memory) using plugin sandbox PluginSandbox sandbox = new PluginSandbox(); sandbox.setConfig(pluginConfig); sandbox.setStrict(false); String rootDir = File.separator + "tmp" + File.separator+ "plugin1_" + System.currentTimeMillis(); Reporter.log("Test for " + zipFileName + ". Dir is " + rootDir,true); //add the individual items to sandbox sandbox.setRootDir(new File(rootDir, pluginConfig.getPlugin())); Enumeration<? extends ZipEntry> entries = orgZipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } sandbox.makeItemFromZipEntry(orgZipFile, entry); } Assert.assertEquals(sandbox.getPluginName(),pluginName); Assert.assertEquals(sandbox.getDescription(),pluginConfig.getDescription()); //get ready to install plugin Map<String, PluginTransportItem> payload = Maps.newHashMap(); for (PluginSandboxItem item : sandbox.getItems(null)) { try { PluginTransportItem payloadItem = item.makeTransportItem(); payload.put(item.getURI().toString(), payloadItem); } catch (Exception ex) { Reporter.log("Exception creating plugin " +ex.getMessage(),true); } } //install the plugin using the http api pluginApi.installPlugin(sandbox.makeManifest(null), payload); installedSet.add(pluginName); HttpDecisionApi decisionApi = new HttpDecisionApi(helper.getRaptureLogin()); try { Thread.sleep(5000); } catch (Exception e) {} Map <String,Object> ctxMap1=JacksonUtil.getMapFromJson(ctxString); Map <String,String> ctxMap2= new HashMap<String,String>(); for (String currKey : ctxMap1.keySet()) ctxMap2.put(currKey, ctxMap1.get(currKey).toString()); String workOrderURI = decisionApi.createWorkOrder(workflowUri,ctxMap2); Reporter.log("Creating work order "+workOrderURI + " with context map "+ctxMap2.toString(),true); int numRetries=0; long waitTimeMS=5000; while (IntegrationTestHelper.isWorkOrderRunning(decisionApi,workOrderURI) && numRetries < 20) { Reporter.log("Checking workorder status, retry count="+numRetries+", waiting "+(waitTimeMS/1000)+" seconds...",true); try { Thread.sleep(waitTimeMS); } catch (Exception e) {} numRetries++; } Reporter.log("Checking results for work order "+workOrderURI,true); Assert.assertEquals(decisionApi.getWorkOrderStatus(workOrderURI).getStatus(),WorkOrderExecutionState.FINISHED); String woResult=decisionApi.getContextValue(workOrderURI+"#0", "TEST_RESULTS"); if (woResult !=null) Assert.assertTrue (Boolean.parseBoolean(woResult)); } private byte[] getContentFromEntry(ZipFile zip, ZipEntry entry) throws IOException { return PluginContentReader.readFromStream(zip.getInputStream(entry)); } private PluginConfig getPluginConfigFromZip(String filename) { File zip = new File(filename); if (!zip.exists() || !zip.canRead()) { return null; } try (ZipFile zipFile = new ZipFile(zip)) { ZipEntry configEntry = zipFile.getEntry(PluginSandbox.PLUGIN_TXT); if (PluginSandbox.PLUGIN_TXT.equals(configEntry.getName())) { try { return JacksonUtil.objectFromJson(getContentFromEntry(zipFile, configEntry), PluginConfig.class); } catch (Exception ex) { throw RaptureExceptionFactory.create("pluing.txt manifest corrupt in zip file " + filename); } } else { Reporter.log("No plugin.txt present in root level of zipfile: " + filename,true); } } catch (IOException e) { Reporter.log("Got IOException: "+e.getMessage(),true); } return null; } @Test(groups = { "plugin", "nightly" }) public void testGetPluginItem() throws IOException { String tableUri = "table://foo/bar"; String indexUri = "index://baz"; HttpIndexApi index = helper.getIndexApi(); index.createTable(tableUri, "TABLE {} USING MONGO { prefix=\"foo\"}"); index.createIndex(indexUri, "field1($1) number"); String pluginName = "Jeff" + System.currentTimeMillis(); pluginApi.createManifest(pluginName); pluginApi.addManifestItem(pluginName, tableUri); pluginApi.addManifestItem(pluginName, indexUri); Map<String, String> verify = pluginApi.verifyPlugin(pluginName); Assert.assertEquals(verify.size(), 2); for (String key : verify.keySet()) { Assert.assertEquals(verify.get(key), "Verified",key +" was not verified"); } String plug = pluginApi.exportPlugin(pluginName, "/tmp/" + pluginName); Map<String, Object> map = JacksonUtil.getMapFromJson(plug); Assert.assertEquals(map.get("objectCount"), new Integer(2)); String path = "/tmp/" + pluginName + "/" + map.get("filePath").toString(); // If API server is local you can check the zip file is correct. if ((new File(path)).exists()) { ZipFile zip = new ZipFile(path); Enumeration<? extends ZipEntry> ennui = zip.entries(); while (ennui.hasMoreElements()) { ZipEntry ze = ennui.nextElement(); String name = ze.getName(); Map<String, Object> contents = null; try (BufferedReader br = new BufferedReader(new InputStreamReader(zip.getInputStream(ze)))) { contents = JacksonUtil.getMapFromJson(br.lines().collect(Collectors.joining())); } Assert.assertNotNull(contents); switch (name) { case "plugin.txt": Assert.assertEquals(pluginName, contents.get("plugin").toString()); break; case "content/foo/bar.table": Assert.assertEquals("foo", contents.get("authority").toString()); Assert.assertEquals("bar", contents.get("name").toString()); Assert.assertEquals("TABLE {} USING MONGO { prefix=\"foo\"}", contents.get("config").toString()); break; case "content/baz/.index": Assert.assertEquals("baz", contents.get("name").toString()); Assert.assertEquals("field1($1) number", contents.get("config").toString()); break; default: Assert.fail("Unexpected file " + name + " in plugin zip "); } } zip.close(); } pluginApi.uninstallPlugin(pluginName); } @Test(groups = { "plugin", "nightly" }) public void testVerifyPlugin() throws IOException { RaptureURI docRepo = helper.getRandomAuthority(Scheme.DOCUMENT); HttpDocApi docApi = helper.getDocApi(); docApi.createDocRepo(docRepo.toString(), "NREP {} USING MEMORY { prefix=\"foo\"}"); String doc1 = RaptureURI.builder(docRepo).docPath("foo/doc1").asString(); String doc2 = RaptureURI.builder(docRepo).docPath("bar/doc2").asString(); String doc3 = RaptureURI.builder(docRepo).docPath("baz/doc3").asString(); docApi.putDoc(doc1, "{ \"val\" : \"foo\" }"); docApi.putDoc(doc2, "{ \"val\" : \"bar\" }"); docApi.putDoc(doc3, "{ \"val\" : \"baz\" }"); String pluginName = "Jeff" + System.currentTimeMillis(); pluginApi.createManifest(pluginName); pluginApi.addManifestItem(pluginName, doc1); pluginApi.addManifestItem(pluginName, doc2); pluginApi.addManifestItem(pluginName, doc3); pluginApi.addManifestItem(pluginName, docRepo.toString()); pluginApi.exportPlugin(pluginName, "/tmp/" + pluginName + ".zip"); Map<String, String> verify = pluginApi.verifyPlugin(pluginName); Assert.assertNotNull(verify); } @AfterClass(groups={"plugin", "nightly"}) public void AfterTest(){ //delete all plugins installed during test for (String p :installedSet) pluginApi.uninstallPlugin(p); } @DataProvider(name = "workflowPluginZips") public Object[][] workflowPluginZips() { return new Object[][] { {"testseries.zip","testseries","Test workflow with series","workflow://testplugin/testseries/createsquaresandverify","{\"SERIES_SIZE\":\"40\"}"}, {"testblob.zip","testblob","Test workflow with blobs","workflow://testplugin/testblob/createblobandverify","{\"BLOB_SIZE\":\"40\"}"}, {"testdoc.zip","testdoc","Test workflow with docs","workflow://testplugin/testdoc/createdocsandverify","{\"DOC_SIZE\":\"40\"}"}, }; } @DataProvider(name = "pluginZips") public Object[][] pluginZips() { return new Object[][] { {"testdoc","testdoc.zip","Test workflow with docs"}, {"testdocplugin","testdocplugin.zip","Test document plugin with data"}, {"testplugin","testplugin.zip","Test plugin with different types"}, }; } }
package org.radarcns.management.web.rest; import com.codahale.metrics.annotation.Timed; import io.github.jhipster.web.util.ResponseUtil; import org.radarcns.auth.authorization.AuthoritiesConstants; import org.radarcns.management.service.RoleService; import org.radarcns.management.service.dto.RoleDTO; import org.radarcns.management.web.rest.util.HeaderUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import static org.radarcns.auth.authorization.Permission.ROLE_CREATE; import static org.radarcns.auth.authorization.Permission.ROLE_READ; import static org.radarcns.auth.authorization.Permission.ROLE_UPDATE; import static org.radarcns.auth.authorization.RadarAuthorization.checkPermissionOnProject; import static org.radarcns.management.security.SecurityUtils.getJWT; /** * REST controller for managing Role. */ @RestController @RequestMapping("/api") public class RoleResource { private final Logger log = LoggerFactory.getLogger(RoleResource.class); private static final String ENTITY_NAME = "role"; @Autowired private RoleService roleService; @Autowired private HttpServletRequest servletRequest; /** * POST /Roles : Create a new role. * * @param roleDTO the roleDTO to create * @return the ResponseEntity with status 201 (Created) and with body the new RoleDTO, or with status 400 (Bad Request) if the Role has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/roles") @Timed public ResponseEntity<RoleDTO> createRole(@Valid @RequestBody RoleDTO roleDTO) throws URISyntaxException { log.debug("REST request to save Role : {}", roleDTO); checkPermissionOnProject(getJWT(servletRequest), ROLE_CREATE, roleDTO.getProjectName()); if (roleDTO.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new role cannot already have an ID")).body(null); } RoleDTO result = roleService.save(roleDTO); return ResponseEntity.created(new URI("/api/roles/" + result.getProjectName() + "/" + result.getAuthorityName())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getProjectName() + "/" + result.getAuthorityName())) .body(result); } /** * PUT /roles : Updates an existing role. * * @param roleDTO the roleDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated roleDTO, * or with status 400 (Bad Request) if the roleDTO is not valid, * or with status 500 (Internal Server Error) if the roleDTO couldnt be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/roles") @Timed public ResponseEntity<RoleDTO> updateRole(@Valid @RequestBody RoleDTO roleDTO) throws URISyntaxException { log.debug("REST request to update Role : {}", roleDTO); if (roleDTO.getId() == null) { return createRole(roleDTO); } checkPermissionOnProject(getJWT(servletRequest), ROLE_UPDATE, roleDTO.getProjectName()); RoleDTO result = roleService.save(roleDTO); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, roleDTO.getId().toString())) .body(result); } /** * GET /roles : get all the roles. * * @return the ResponseEntity with status 200 (OK) and the list of roles in body */ @GetMapping("/roles") @Timed @Secured( {AuthoritiesConstants.PROJECT_ADMIN, AuthoritiesConstants.SYS_ADMIN}) public List<RoleDTO> getAllRoles() { log.debug("REST request to get all Roles"); return roleService.findAll(); } /** * GET /roles : get all the roles. * * @return the ResponseEntity with status 200 (OK) and the list of roles in body */ @GetMapping("/roles/admin") @Timed public List<RoleDTO> getAllAdminRoles() { log.debug("REST request to get all Admin Roles"); return roleService.findSuperAdminRoles(); } /** * GET /roles/:projectName/:authorityName : get the role of the specified project and authority * * @param projectName The project name * @param authorityName The authority name * @return the ResponseEntity with status 200 (OK) and with body the roleDTO, or with status 404 (Not Found) */ @GetMapping("/roles/{projectName}/{authorityName}") @Timed public ResponseEntity<RoleDTO> getRole(@PathVariable String projectName, @PathVariable String authorityName) { checkPermissionOnProject(getJWT(servletRequest), ROLE_READ, projectName); return ResponseUtil.wrapOrNotFound(roleService .findOneByProjectNameAndAuthorityName(projectName, authorityName)); } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4915.ArcadeDriveRobot; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc4915.ArcadeDriveRobot.commands.*; import org.usfirst.frc4915.ArcadeDriveRobot.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; public static OI oi; public double kThrottleValueRAW; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static DriveTrain driveTrain; public static Harvester harvester; public static AirCompressor airCompressor; public static Launcher launcher; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static final String VERSION = "v1.05.01"; // Added Launcher (single solenoid) gearbox pneumatics functionality // Includes a Gyro, and limit switch /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrain = new DriveTrain(); harvester = new Harvester(); airCompressor = new AirCompressor(); launcher = new Launcher(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // This MUST be here. If the OI creates Commands (which it very likely // will), constructing it during the construction of CommandBase (from // which commands extend), subsystems are not guaranteed to be // yet. Thus, their requires() statements may grab null pointers. Bad // news. Don't move it. oi = new OI(); // instantiate the command used for the autonomous period // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS autonomousCommand = new AutonomousCommand(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS System.out.println(VERSION); SendUserMessages messages = new SendUserMessages(); messages.display(1, "Hi 456789012345678901234567890"); //tests the SendUserMessages, 30 characters messages.display(2, "Hi2456789012345678901234567890"); //tests the SendUserMessages, 30 characters messages.display(3, "Hi3456789012345678901234567890"); //tests the SendUserMessages, 30 characters Robot.airCompressor.start(); } public void autonomousInit() { // schedule the autonomous command (example) if (autonomousCommand != null) autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) autonomousCommand.cancel(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); SmartDashboard.putBoolean("Pressure Switch", RobotMap.airCompressorCompressor.getPressureSwitchValue()); SmartDashboard.putNumber("Throttle", oi.getJoystickDrive().getAxis(Joystick.AxisType.kThrottle)); SmartDashboard.putNumber("NumAxis", oi.getJoystickDrive().getAxis(Joystick.AxisType.kNumAxis)); SmartDashboard.putNumber("X", oi.getJoystickDrive().getAxis(Joystick.AxisType.kX)); SmartDashboard.putNumber("Z", oi.getJoystickDrive().getAxis(Joystick.AxisType.kZ)); SmartDashboard.putNumber("Y", oi.getJoystickDrive().getAxis(Joystick.AxisType.kY)); SmartDashboard.putNumber("Twist", oi.getJoystickDrive().getAxis(Joystick.AxisType.kTwist)); kThrottleValueRAW = oi.joystickDrive.getAxis(Joystick.AxisType.kThrottle); SmartDashboard.putNumber("kThrottle ", .5 * ( -1 * kThrottleValueRAW + 1)); // Advanced Joystick Throttle // SmartDashboard.putNumber("Z Axis ", oi.joystickDrive.getAxis(Joystick.AxisType.kZ)); // Attack Joystick Throttle SmartDashboard.putBoolean("Harvester Limit Switch1: ", harvester.getLimitSwitch1()); } /** * This function called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
package skadistats.clarity.examples.serializers; import com.google.protobuf.CodedInputStream; import com.google.protobuf.ZeroCopy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import skadistats.clarity.model.s2.field.FieldType; import skadistats.clarity.processor.reader.OnMessage; import skadistats.clarity.processor.runner.Context; import skadistats.clarity.processor.runner.ControllableRunner; import skadistats.clarity.source.MappedFileSource; import skadistats.clarity.wire.Packet; import skadistats.clarity.wire.common.proto.Demo; import skadistats.clarity.wire.s2.proto.S2NetMessages; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Set; import java.util.TreeSet; public class Main { private final Logger log = LoggerFactory.getLogger(Main.class.getPackage().getClass()); @OnMessage(Demo.CDemoSendTables.class) public void onSendTables(Context ctx, Demo.CDemoSendTables message) throws IOException { CodedInputStream cis = CodedInputStream.newInstance(ZeroCopy.extract(message.getData())); int size = cis.readRawVarint32(); S2NetMessages.CSVCMsg_FlattenedSerializer fs = Packet.parse(S2NetMessages.CSVCMsg_FlattenedSerializer.class, ZeroCopy.wrap(cis.readRawBytes(size))); Set<String> baseTypes = new TreeSet<>(); for (S2NetMessages.ProtoFlattenedSerializer_t s : fs.getSerializersList()) { for (int fi : s.getFieldsIndexList()) { S2NetMessages.ProtoFlattenedSerializerField_t f = fs.getFields(fi); FieldType ft = new FieldType(fs.getSymbols(f.getVarTypeSym())); if (!f.hasFieldSerializerNameSym()) { int l = 0; do { baseTypes.add(ft.getBaseType().toUpperCase()); if ("CUTLVECTOR".equals(ft.getBaseType().toUpperCase())) { ft = ft.getGenericType(); } else { ft = null; } l++; } while (l <= 1 && ft != null); } } } dump(fs); } private void dump(S2NetMessages.CSVCMsg_FlattenedSerializer fs) throws FileNotFoundException { PrintStream out = new PrintStream(new FileOutputStream("flattables.txt")); for (S2NetMessages.ProtoFlattenedSerializer_t s : fs.getSerializersList()) { out.println(" out.format("%s(%s)\n", fs.getSymbols(s.getSerializerNameSym()), s.getSerializerVersion()); out.println(" for (int fi : s.getFieldsIndexList()) { S2NetMessages.ProtoFlattenedSerializerField_t f = fs.getFields(fi); String line = String.format( "type: %-50s name: %-30s node: %-41s serializer: %-35s flags: %8s bitcount: %3s low: %9s high: %9s", String.format("%s%s", fs.getSymbols(f.getVarTypeSym()), f.hasVarEncoderSym() ? String.format(" {%s}", fs.getSymbols(f.getVarEncoderSym())) : ""), fs.getSymbols(f.getVarNameSym()), fs.getSymbols(f.getSendNodeSym()), f.hasFieldSerializerNameSym() ? String.format("%s(%s)", fs.getSymbols(f.getFieldSerializerNameSym()), f.getFieldSerializerVersion()) : "-", f.hasEncodeFlags() ? Integer.toHexString(f.getEncodeFlags()) : "-", f.hasBitCount() ? f.getBitCount() : "-", f.hasLowValue() ? f.getLowValue() : "-", f.hasHighValue() ? f.getHighValue() : "-" ); out.println(line); } out.println(); out.println(); } } public void run(String[] args) throws Exception { long tStart = System.currentTimeMillis(); ControllableRunner runner = new ControllableRunner(new MappedFileSource(args[0])).runWith(this); runner.tick(); runner.halt(); long tMatch = System.currentTimeMillis() - tStart; log.info("total time taken: {}s", (tMatch) / 1000.0); } public static void main(String[] args) throws Exception { new Main().run(args); } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc4915.ArcadeDriveRobot; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc4915.ArcadeDriveRobot.commands.*; import org.usfirst.frc4915.ArcadeDriveRobot.subsystems.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { Command autonomousCommand; public static OI oi; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static DriveTrain driveTrain; public static Harvester harvester; public static AirCompressor airCompressor; public static Launcher launcher; public static Gyroscope gyroscope; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS //UPDATE VERSION NUMBER IN Version.java FROM NOW ON public static double batteryVoltage; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotMap.init(); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrain = new DriveTrain(); harvester = new Harvester(); airCompressor = new AirCompressor(); launcher = new Launcher(); gyroscope = new Gyroscope(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS // This MUST be here. If the OI creates Commands (which it very likely // will), constructing it during the construction of CommandBase (from // which commands extend), subsystems are not guaranteed to be // yet. Thus, their requires() statements may grab null pointers. Bad // news. Don't move it. oi = new OI(); // instantiate the command used for the autonomous period // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS autonomousCommand = new AutonomousCommandGroup(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS System.out.println("Starting Spartronics Robot: " + Version.getVersion()); SendUserMessages.display(1, Version.getVersion()); //SendUserMessages Limit to 20 characters SendUserMessages.display(2, "Check joystick order!!!!!"); if (gyroscope != null) { gyroscope.reset(); } else { SendUserMessages.display(3, "Gyroscope absent!!!"); } if (airCompressor != null) { airCompressor.start(); } if (harvester != null && !RobotMap.launcherLimitSwitchForLauncherDown.get()) { if (harvester.isHarvesterUp()) { harvester.retractPneumatics(); } else { harvester.extendPneumatics(); } harvester.stopWheels(); } if (launcher != null) { launcher.pneumaticsReverse(); } driveTrain.joystickThrottle = driveTrain.modifyThrottle(); } public void autonomousInit() { // schedule the autonomous command (example) if (autonomousCommand != null) { autonomousCommand.start(); } } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != null) { autonomousCommand.cancel(); } } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); SmartDashboard.putNumber("Gyroscope", gyroscope.getAngle()); SmartDashboard.putBoolean("Launcher Limit Switch", launcher.getLimitSwitchForLauncherDownValue()); SmartDashboard.putData(Scheduler.getInstance()); batteryVoltage = DriverStation.getInstance().getBatteryVoltage(); SmartDashboard.putNumber("BatteryVoltage: ", batteryVoltage); } /** * This function called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } }
package org.tndata.android.compass.model; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import org.tndata.android.compass.parser.ParserModels; import java.util.ArrayList; import java.util.List; /** * Model class for user behaviors. * * @author Ismael Alonso * @version 1.0.0 */ public class UserBehavior extends UserContent implements Parcelable, ParserModels.ResultSet{ public static final String TYPE = "userbehavior"; //Values retrieved from the API @SerializedName("behavior") private TDCBehavior mBehavior; @SerializedName("parent_usergoal") private UserGoal mParentUserGoal; @SerializedName("parent_usercategory") private UserCategory mParentUserCategory; //Values set during post-processing private List<UserGoal> userGoals = new ArrayList<>(); private List<UserAction> userActions = new ArrayList<>(); public UserBehavior(TDCBehavior behavior){ this.mBehavior = behavior; } public void setGoals(List<UserGoal> goals) { this.userGoals = goals; } public void setActions(List<UserAction> actions){ this.userActions = actions; } public TDCBehavior getBehavior(){ return mBehavior; } @Override public long getContentId(){ return mBehavior.getId(); } public String getTitle(){ return mBehavior.getTitle(); } public String getDescription(){ return mBehavior.getDescription(); } public String getHTMLDescription(){ return mBehavior.getHTMLDescription(); } public String getIconUrl(){ return mBehavior.getIconUrl(); } public List<UserGoal> getGoals(){ return userGoals; } public List<UserAction> getActions(){ return userActions; } public UserGoal getParentUserGoal(){ return mParentUserGoal; } public UserCategory getParentUserCategory(){ return mParentUserCategory; } @Override protected String getType(){ return TYPE; } @Override public void init(){ if (userGoals == null){ userGoals = new ArrayList<>(); } if (userActions == null){ userActions = new ArrayList<>(); } } public void addGoal(UserGoal goal){ if (!userGoals.contains(goal)){ userGoals.add(goal); } } public void removeGoal(UserGoal goal){ if (userGoals.contains(goal)){ userGoals.remove(goal); } } public void addAction(UserAction action){ if (!userActions.contains(action)){ userActions.add(action); } } public void removeAction(UserAction action){ if (userActions.contains(action)){ userActions.remove(action); } } @Override public String toString(){ return "UserBehavior #" + getId() + " (" + mBehavior.toString() + ")"; } @Override public int describeContents(){ return 0; } @Override public void writeToParcel(Parcel dest, int flags){ super.addToParcel(dest, flags); dest.writeParcelable(mBehavior, flags); } public static final Creator<UserBehavior> CREATOR = new Creator<UserBehavior>(){ @Override public UserBehavior createFromParcel(Parcel source){ return new UserBehavior(source); } @Override public UserBehavior[] newArray(int size){ return new UserBehavior[size]; } }; private UserBehavior(Parcel src){ super(src); mBehavior = src.readParcelable(TDCBehavior.class.getClassLoader()); } }
package zmaster587.advancedRocketry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import micdoodle8.mods.galacticraft.core.util.ConfigManagerCore; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import zmaster587.advancedRocketry.achievements.ARAchivements; import zmaster587.advancedRocketry.api.*; import zmaster587.advancedRocketry.api.atmosphere.AtmosphereRegister; import zmaster587.advancedRocketry.api.dimension.solar.StellarBody; import zmaster587.advancedRocketry.api.fuel.FuelRegistry; import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType; import zmaster587.advancedRocketry.api.satellite.SatelliteProperties; import zmaster587.advancedRocketry.armor.ItemSpaceArmor; import zmaster587.advancedRocketry.atmosphere.AtmosphereVacuum; import zmaster587.advancedRocketry.backwardCompat.VersionCompat; import zmaster587.advancedRocketry.block.BlockCharcoalLog; import zmaster587.advancedRocketry.block.BlockCrystal; import zmaster587.advancedRocketry.block.BlockDoor2; import zmaster587.advancedRocketry.block.BlockElectricMushroom; import zmaster587.advancedRocketry.block.BlockFluid; import zmaster587.advancedRocketry.block.BlockGeneric; import zmaster587.advancedRocketry.block.BlockIntake; import zmaster587.advancedRocketry.block.BlockLandingPad; import zmaster587.advancedRocketry.block.BlockLaser; import zmaster587.advancedRocketry.block.BlockLightSource; import zmaster587.advancedRocketry.block.BlockLinkedHorizontalTexture; import zmaster587.advancedRocketry.block.BlockMiningDrill; import zmaster587.advancedRocketry.block.BlockPlanetSoil; import zmaster587.advancedRocketry.block.BlockPress; import zmaster587.advancedRocketry.block.BlockPressurizedFluidTank; import zmaster587.advancedRocketry.block.BlockQuartzCrucible; import zmaster587.advancedRocketry.block.BlockRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockRocketMotor; import zmaster587.advancedRocketry.block.BlockRotatableModel; import zmaster587.advancedRocketry.block.BlockSeat; import zmaster587.advancedRocketry.block.BlockFuelTank; import zmaster587.advancedRocketry.block.BlockSolarPanel; import zmaster587.advancedRocketry.block.BlockStationModuleDockingPort; import zmaster587.advancedRocketry.block.BlockTileNeighborUpdate; import zmaster587.advancedRocketry.block.BlockTileRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockWarpCore; import zmaster587.advancedRocketry.block.BlockWarpShipMonitor; import zmaster587.advancedRocketry.block.cable.BlockDataCable; import zmaster587.advancedRocketry.block.cable.BlockEnergyPipe; import zmaster587.advancedRocketry.block.cable.BlockLiquidPipe; import zmaster587.advancedRocketry.block.multiblock.BlockARHatch; import zmaster587.advancedRocketry.block.plant.BlockAlienLeaves; import zmaster587.advancedRocketry.block.plant.BlockAlienSapling; import zmaster587.advancedRocketry.block.plant.BlockAlienWood; import zmaster587.advancedRocketry.block.BlockTorchUnlit; import zmaster587.advancedRocketry.command.WorldCommand; import zmaster587.advancedRocketry.common.CommonProxy; import zmaster587.advancedRocketry.dimension.DimensionManager; import zmaster587.advancedRocketry.dimension.DimensionProperties; import zmaster587.advancedRocketry.entity.EntityDummy; import zmaster587.advancedRocketry.entity.EntityLaserNode; import zmaster587.advancedRocketry.entity.EntityRocket; import zmaster587.advancedRocketry.entity.EntityStationDeployedRocket; import zmaster587.advancedRocketry.event.BucketHandler; import zmaster587.advancedRocketry.event.CableTickHandler; import zmaster587.advancedRocketry.event.PlanetEventHandler; import zmaster587.advancedRocketry.event.WorldEvents; import zmaster587.advancedRocketry.integration.CompatibilityMgr; import zmaster587.advancedRocketry.integration.GalacticCraftHandler; import zmaster587.libVulpes.inventory.GuiHandler; import zmaster587.libVulpes.items.ItemBlockMeta; import zmaster587.libVulpes.items.ItemIngredient; import zmaster587.libVulpes.items.ItemProjector; import zmaster587.advancedRocketry.item.*; import zmaster587.advancedRocketry.item.components.ItemJetpack; import zmaster587.advancedRocketry.item.components.ItemPressureTank; import zmaster587.advancedRocketry.item.components.ItemUpgrade; import zmaster587.advancedRocketry.mission.MissionGasCollection; import zmaster587.advancedRocketry.mission.MissionOreMining; import zmaster587.advancedRocketry.network.PacketAtmSync; import zmaster587.advancedRocketry.network.PacketBiomeIDChange; import zmaster587.advancedRocketry.network.PacketDimInfo; import zmaster587.advancedRocketry.network.PacketOxygenState; import zmaster587.advancedRocketry.network.PacketSatellite; import zmaster587.advancedRocketry.network.PacketSpaceStationInfo; import zmaster587.advancedRocketry.network.PacketStationUpdate; import zmaster587.advancedRocketry.network.PacketStellarInfo; import zmaster587.advancedRocketry.network.PacketStorageTileUpdate; import zmaster587.advancedRocketry.satellite.SatelliteBiomeChanger; import zmaster587.advancedRocketry.satellite.SatelliteComposition; import zmaster587.advancedRocketry.satellite.SatelliteDensity; import zmaster587.advancedRocketry.satellite.SatelliteEnergy; import zmaster587.advancedRocketry.satellite.SatelliteMassScanner; import zmaster587.advancedRocketry.satellite.SatelliteOptical; import zmaster587.advancedRocketry.satellite.SatelliteOreMapping; import zmaster587.advancedRocketry.stations.SpaceObject; import zmaster587.advancedRocketry.stations.SpaceObjectManager; import zmaster587.advancedRocketry.tile.Satellite.TileEntitySatelliteControlCenter; import zmaster587.advancedRocketry.tile.Satellite.TileSatelliteBuilder; import zmaster587.advancedRocketry.tile.*; import zmaster587.advancedRocketry.tile.cables.TileDataPipe; import zmaster587.advancedRocketry.tile.cables.TileEnergyPipe; import zmaster587.advancedRocketry.tile.cables.TileLiquidPipe; import zmaster587.advancedRocketry.tile.hatch.TileDataBus; import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityFuelingStation; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityMoniteringStation; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidUnloader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketUnloader; import zmaster587.advancedRocketry.tile.multiblock.*; import zmaster587.advancedRocketry.tile.multiblock.TileSpaceLaser; import zmaster587.advancedRocketry.tile.multiblock.energy.TileMicrowaveReciever; import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser; import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe; import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler; import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine; import zmaster587.advancedRocketry.tile.oxygen.TileCO2Scrubber; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenCharger; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenVent; import zmaster587.advancedRocketry.tile.station.TileDockingPort; import zmaster587.advancedRocketry.tile.station.TileLandingPad; import zmaster587.advancedRocketry.tile.station.TileStationAltitudeController; import zmaster587.advancedRocketry.tile.station.TileStationGravityController; import zmaster587.advancedRocketry.tile.station.TileStationOrientationControl; import zmaster587.advancedRocketry.tile.station.TileWarpShipMonitor; import zmaster587.advancedRocketry.util.FluidColored; import zmaster587.advancedRocketry.util.SealableBlockHandler; import zmaster587.advancedRocketry.util.XMLPlanetLoader; import zmaster587.advancedRocketry.world.biome.BiomeGenAlienForest; import zmaster587.advancedRocketry.world.biome.BiomeGenCrystal; import zmaster587.advancedRocketry.world.biome.BiomeGenDeepSwamp; import zmaster587.advancedRocketry.world.biome.BiomeGenHotDryRock; import zmaster587.advancedRocketry.world.biome.BiomeGenMoon; import zmaster587.advancedRocketry.world.biome.BiomeGenMarsh; import zmaster587.advancedRocketry.world.biome.BiomeGenOceanSpires; import zmaster587.advancedRocketry.world.biome.BiomeGenSpace; import zmaster587.advancedRocketry.world.biome.BiomeGenStormland; import zmaster587.advancedRocketry.world.decoration.MapGenLander; import zmaster587.advancedRocketry.world.ore.OreGenerator; import zmaster587.advancedRocketry.world.provider.WorldProviderPlanet; import zmaster587.advancedRocketry.world.provider.WorldProviderSpace; import zmaster587.advancedRocketry.world.type.WorldTypePlanetGen; import zmaster587.advancedRocketry.world.type.WorldTypeSpace; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.LibVulpesBlocks; import zmaster587.libVulpes.api.LibVulpesItems; import zmaster587.libVulpes.api.material.AllowedProducts; import zmaster587.libVulpes.api.material.MaterialRegistry; import zmaster587.libVulpes.api.material.MixedMaterial; import zmaster587.libVulpes.block.BlockAlphaTexture; import zmaster587.libVulpes.block.BlockMeta; import zmaster587.libVulpes.block.BlockTile; import zmaster587.libVulpes.block.multiblock.BlockMultiBlockComponentVisible; import zmaster587.libVulpes.block.multiblock.BlockMultiblockMachine; import zmaster587.libVulpes.network.PacketHandler; import zmaster587.libVulpes.network.PacketItemModifcation; import zmaster587.libVulpes.recipe.NumberedOreDictStack; import zmaster587.libVulpes.recipe.RecipesMachine; import zmaster587.libVulpes.tile.TileMaterial; import zmaster587.libVulpes.tile.multiblock.TileMultiBlock; import zmaster587.libVulpes.util.InputSyncHandler; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.logging.Logger; @Mod(modid="advancedRocketry", name="Advanced Rocketry", version="%VERSION%", dependencies="required-after:libVulpes@[%LIBVULPESVERSION%,)") public class AdvancedRocketry { @SidedProxy(clientSide="zmaster587.advancedRocketry.client.ClientProxy", serverSide="zmaster587.advancedRocketry.common.CommonProxy") public static CommonProxy proxy; public final static String version = "%VERSION%"; @Instance(value = Constants.modId) public static AdvancedRocketry instance; public static WorldType planetWorldType; public static WorldType spaceWorldType; public static CompatibilityMgr compat = new CompatibilityMgr(); public static Logger logger = Logger.getLogger(Constants.modId); private static Configuration config; private static final String BIOMECATETORY = "Biomes"; String[] sealableBlockWhileList; public MaterialRegistry materialRegistry = new MaterialRegistry(); private HashMap<AllowedProducts, HashSet<String>> modProducts = new HashMap<AllowedProducts, HashSet<String>>(); private static CreativeTabs tabAdvRocketry = new CreativeTabs("advancedRocketry") { @Override public Item getTabIconItem() { return AdvancedRocketryItems.itemSatelliteIdChip; } }; @EventHandler public void preInit(FMLPreInitializationEvent event) { //Init API DimensionManager.planetWorldProvider = WorldProviderPlanet.class; AdvancedRocketryAPI.atomsphereSealHandler = SealableBlockHandler.INSTANCE; ((SealableBlockHandler)AdvancedRocketryAPI.atomsphereSealHandler).loadDefaultData(); config = new Configuration(new File(event.getModConfigurationDirectory(), "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/advancedRocketry.cfg")); config.load(); final String oreGen = "Ore Generation"; final String ROCKET = "Rockets"; final String MOD_INTERACTION = "Mod Interaction"; final String PLANET = "Planet"; final String ASTEROID = "Asteroid"; final String GAS_MINING = "GasMining"; final String PERFORMANCE = "Performance"; AtmosphereVacuum.damageValue = (int) config.get(Configuration.CATEGORY_GENERAL, "vacuumDamage", 1, "Amount of damage taken every second in a vacuum").getInt(); zmaster587.advancedRocketry.api.Configuration.buildSpeedMultiplier = (float) config.get(Configuration.CATEGORY_GENERAL, "buildSpeedMultiplier", 1f, "Multiplier for the build speed of the Rocket Builder (0.5 is twice as fast 2 is half as fast").getDouble(); zmaster587.advancedRocketry.api.Configuration.spaceDimId = config.get(Configuration.CATEGORY_GENERAL,"spaceStationId" , -2,"Dimension ID to use for space stations").getInt(); zmaster587.advancedRocketry.api.Configuration.enableOxygen = config.get(Configuration.CATEGORY_GENERAL, "EnableAtmosphericEffects", true, "If true, allows players being hurt due to lack of oxygen and allows effects from non-standard atmosphere types").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods = config.get(Configuration.CATEGORY_GENERAL, "makeMaterialsForOtherMods", true, "If true the machines from AdvancedRocketry will produce things like plates/rods for other mods even if Advanced Rocketry itself does not use the material (This can increase load time)").getBoolean(); zmaster587.advancedRocketry.api.Configuration.scrubberRequiresCartrige = config.get(Configuration.CATEGORY_GENERAL, "scrubberRequiresCartrige", true, "If true the Oxygen scrubbers require a consumable carbon collection cartridge").getBoolean(); zmaster587.advancedRocketry.api.Configuration.enableLaserDrill = config.get(Configuration.CATEGORY_GENERAL, "EnableLaserDrill", true, "Enables the laser drill machine").getBoolean(); zmaster587.advancedRocketry.api.Configuration.spaceLaserPowerMult = (float)config.get(Configuration.CATEGORY_GENERAL, "LaserDrillPowerMultiplier", 1d, "Power multiplier for the laser drill machine").getDouble(); zmaster587.advancedRocketry.api.Configuration.enableTerraforming = config.get(Configuration.CATEGORY_GENERAL, "EnableTerraforming", true,"Enables terraforming items and blocks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.spaceSuitOxygenTime = config.get(Configuration.CATEGORY_GENERAL, "spaceSuitO2Buffer", 30, "Maximum time in minutes that the spacesuit's internal buffer can store O2 for").getInt(); zmaster587.advancedRocketry.api.Configuration.travelTimeMultiplier = (float)config.get(Configuration.CATEGORY_GENERAL, "warpTravelTime", 1f, "Multiplier for warp travel time").getDouble(); zmaster587.advancedRocketry.api.Configuration.maxBiomesPerPlanet = config.get(Configuration.CATEGORY_GENERAL, "maxBiomesPerPlanet", 5, "Maximum unique biomes per planet, -1 to disable").getInt(); zmaster587.advancedRocketry.api.Configuration.allowTerraforming = config.get(Configuration.CATEGORY_GENERAL, "allowTerraforming", false, "EXPERIMENTAL: If set to true allows contruction and usage of the terraformer. This is known to cause strange world generation after successful terraform").getBoolean(); zmaster587.advancedRocketry.api.Configuration.terraformingBlockSpeed = config.get(Configuration.CATEGORY_GENERAL, "biomeUpdateSpeed", 1, "How many blocks have the biome changed per tick. Large numbers can slow the server down", Integer.MAX_VALUE, 1).getInt(); zmaster587.advancedRocketry.api.Configuration.terraformSpeed = config.get(Configuration.CATEGORY_GENERAL, "terraformMult", 1f, "Multplier for terraforming speed").getDouble(); zmaster587.advancedRocketry.api.Configuration.terraformRequiresFluid = config.get(Configuration.CATEGORY_GENERAL, "TerraformerRequiresFluids", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.canPlayerRespawnInSpace = config.get(Configuration.CATEGORY_GENERAL, "allowPlanetRespawn", false, "If true players will respawn near beds on planets IF the spawn location is in a breathable atmosphere").getBoolean(); DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 0xFFFF, "Dimensions including and after this number are allowed to be made into planets"); zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes = config.getBoolean("blackListVanillaBiomes", PLANET, false, "Prevents any vanilla biomes from spawning on planets"); zmaster587.advancedRocketry.api.Configuration.overrideGCAir = config.get(MOD_INTERACTION, "OverrideGCAir", true, "If true Galaciticcraft's air will be disabled entirely requiring use of Advanced Rocketry's Oxygen system on GC planets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.fuelPointsPerDilithium = config.get(Configuration.CATEGORY_GENERAL, "pointsPerDilithium", 500, "How many units of fuel should each Dilithium Crystal give to warp ships", 1, 1000).getInt(); zmaster587.advancedRocketry.api.Configuration.electricPlantsSpawnLightning = config.get(Configuration.CATEGORY_GENERAL, "electricPlantsSpawnLightning", true, "Should Electric Mushrooms be able to spawn lightning").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood = config.get(Configuration.CATEGORY_GENERAL, "sawMillCutVanillaWood", true, "Should the cutting machine be able to cut vanilla wood into planks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.automaticRetroRockets = config.get(ROCKET, "autoRetroRockets", true, "Setting to false will disable the retrorockets that fire automatically on reentry on both player and automated rockets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.atmosphereHandleBitMask = config.get(PERFORMANCE, "atmosphereCalculationMethod", 0, "BitMask: 0: no threading, radius based; 1: threading, radius based (EXP); 2: no threading volume based; 3: threading volume based (EXP)").getInt(); zmaster587.advancedRocketry.api.Configuration.advancedVFX = config.get(PERFORMANCE, "advancedVFX", true, "Advanced visual effects").getBoolean(); zmaster587.advancedRocketry.api.Configuration.gasCollectionMult = config.get(GAS_MINING, "gasMissionMultiplier", 1.0, "Multiplier for the amount of time gas collection missions take").getDouble(); zmaster587.advancedRocketry.api.Configuration.asteroidMiningMult = config.get(ASTEROID, "miningMissionMultiplier", 1.0, "Multiplier changing how much total material is brought back from a mining mission").getDouble(); zmaster587.advancedRocketry.api.Configuration.standardAsteroidOres = config.get(ASTEROID, "standardOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in asteriods").getStringList(); zmaster587.advancedRocketry.api.Configuration.standardLaserDrillOres = config.get(Configuration.CATEGORY_GENERAL, "laserDrillOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone", "oreDiamond"}, "List of oredictionary names of ores allowed to be mined by the laser drill if surface drilling is disabled").getStringList(); zmaster587.advancedRocketry.api.Configuration.laserDrillPlanet = config.get(Configuration.CATEGORY_GENERAL, "laserDrillPlanet", false, "If true the orbital laser will actually mine blocks on the planet below").getBoolean(); //Client zmaster587.advancedRocketry.api.Configuration.rocketRequireFuel = config.get(ROCKET, "rocketsRequireFuel", true, "Set to false if rockets should not require fuel to fly").getBoolean(); zmaster587.advancedRocketry.api.Configuration.rocketThrustMultiplier = config.get(ROCKET, "thrustMultiplier", 1f, "Multiplier for per-engine thrust").getDouble(); zmaster587.advancedRocketry.api.Configuration.fuelCapacityMultiplier = config.get(ROCKET, "fuelCapacityMultiplier", 1f, "Multiplier for per-tank capacity").getDouble(); //Copper Config zmaster587.advancedRocketry.api.Configuration.generateCopper = config.get(oreGen, "GenerateCopper", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.copperClumpSize = config.get(oreGen, "CopperPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.copperPerChunk = config.get(oreGen, "CopperPerChunk", 10).getInt(); //Tin Config zmaster587.advancedRocketry.api.Configuration.generateTin = config.get(oreGen, "GenerateTin", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.tinClumpSize = config.get(oreGen, "TinPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.tinPerChunk = config.get(oreGen, "TinPerChunk", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateDilithium = config.get(oreGen, "generateDilithium", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.dilithiumClumpSize = config.get(oreGen, "DilithiumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunk = config.get(oreGen, "DilithiumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunkMoon = config.get(oreGen, "DilithiumPerChunkLuna", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateAluminum = config.get(oreGen, "generateAluminum", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.aluminumClumpSize = config.get(oreGen, "AluminumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.aluminumPerChunk = config.get(oreGen, "AluminumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.generateRutile = config.get(oreGen, "GenerateRutile", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.rutileClumpSize = config.get(oreGen, "RutilePerClump", 3).getInt(); zmaster587.advancedRocketry.api.Configuration.rutilePerChunk = config.get(oreGen, "RutilePerChunk", 6).getInt(); sealableBlockWhileList = config.getStringList(Configuration.CATEGORY_GENERAL, "sealableBlockWhiteList", new String[] {}, "Mod:Blockname for example \"minecraft:chest\""); //Satellite config zmaster587.advancedRocketry.api.Configuration.microwaveRecieverMulitplier = 10*(float)config.get(Configuration.CATEGORY_GENERAL, "MicrowaveRecieverMulitplier", 1f, "Multiplier for the amount of energy produced by the microwave reciever").getDouble(); String str[] = config.getStringList("spaceLaserDimIdBlackList", Configuration.CATEGORY_GENERAL, new String[] {}, "Laser drill will not mine these dimension"); //Load laser dimid blacklists for(String s : str) { try { zmaster587.advancedRocketry.api.Configuration.laserBlackListDims.add(Integer.parseInt(s)); } catch (NumberFormatException e) { logger.warning("Invalid number \"" + s + "\" for laser dimid blacklist"); } } config.save(); //Register Packets PacketHandler.addDiscriminator(PacketDimInfo.class); PacketHandler.addDiscriminator(PacketSatellite.class); PacketHandler.addDiscriminator(PacketStellarInfo.class); PacketHandler.addDiscriminator(PacketItemModifcation.class); PacketHandler.addDiscriminator(PacketOxygenState.class); PacketHandler.addDiscriminator(PacketStationUpdate.class); PacketHandler.addDiscriminator(PacketSpaceStationInfo.class); PacketHandler.addDiscriminator(PacketAtmSync.class); PacketHandler.addDiscriminator(PacketBiomeIDChange.class); PacketHandler.addDiscriminator(PacketStorageTileUpdate.class); //if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) MinecraftForge.EVENT_BUS.register(this); SatelliteRegistry.registerSatellite("optical", SatelliteOptical.class); SatelliteRegistry.registerSatellite("solar", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("density", SatelliteDensity.class); SatelliteRegistry.registerSatellite("composition", SatelliteComposition.class); SatelliteRegistry.registerSatellite("mass", SatelliteMassScanner.class); SatelliteRegistry.registerSatellite("asteroidMiner", MissionOreMining.class); SatelliteRegistry.registerSatellite("gasMining", MissionGasCollection.class); SatelliteRegistry.registerSatellite("solarEnergy", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("oreScanner", SatelliteOreMapping.class); SatelliteRegistry.registerSatellite("biomeChanger", SatelliteBiomeChanger.class); AdvancedRocketryBlocks.blocksGeode = new BlockGeneric(MaterialGeode.geode).setBlockName("geode").setCreativeTab(LibVulpes.tabLibVulpesOres).setBlockTextureName("advancedrocketry:geode").setHardness(6f).setResistance(2000F); AdvancedRocketryBlocks.blocksGeode.setHarvestLevel("jackhammer", 2); AdvancedRocketryBlocks.blockLaunchpad = new BlockLinkedHorizontalTexture(Material.rock).setBlockName("pad").setCreativeTab(tabAdvRocketry).setBlockTextureName("advancedrocketry:rocketPad").setHardness(2f).setResistance(10f); AdvancedRocketryBlocks.blockStructureTower = new BlockAlphaTexture(Material.rock).setBlockName("structuretower").setCreativeTab(tabAdvRocketry).setBlockTextureName("advancedrocketry:structuretower").setHardness(2f); AdvancedRocketryBlocks.blockGenericSeat = new BlockSeat(Material.cloth).setBlockName("seat").setCreativeTab(tabAdvRocketry).setBlockTextureName("minecraft:wool_colored_silver").setHardness(0.5f); AdvancedRocketryBlocks.blockEngine = new BlockRocketMotor(Material.rock).setBlockName("rocket").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockFuelTank = new BlockFuelTank(Material.rock).setBlockName("fuelTank").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockSawBlade = new BlockRotatableModel(Material.rock, TileModelRender.models.SAWBLADE.ordinal()).setCreativeTab(tabAdvRocketry).setBlockName("sawBlade").setHardness(2f); AdvancedRocketryBlocks.blockMotor = new BlockRotatableModel(Material.rock, TileModelRender.models.MOTOR.ordinal()).setCreativeTab(tabAdvRocketry).setBlockName("motor").setHardness(2f); AdvancedRocketryBlocks.blockConcrete = new BlockGeneric(Material.rock).setBlockName("concrete").setBlockTextureName("advancedRocketry:rocketPad_noEdge").setCreativeTab(tabAdvRocketry).setHardness(3f).setResistance(16f); AdvancedRocketryBlocks.blockPlatePress = new BlockPress().setBlockName("blockHandPress").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockAirLock = new BlockDoor2(Material.rock).setBlockName("smallAirlockDoor").setBlockTextureName("advancedRocketry:smallAirlockDoor").setHardness(3f).setResistance(8f); AdvancedRocketryBlocks.blockLandingPad = new BlockLandingPad(Material.rock).setBlockName("dockingPad").setBlockTextureName("advancedRocketry:rocketPad_").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenDetection = new BlockRedstoneEmitter(Material.rock,"advancedrocketry:atmosphereDetector_active").setBlockName("atmosphereDetector").setBlockTextureName("advancedRocketry:atmosphereDetector").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenScrubber = new BlockTile(TileCO2Scrubber.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber","advancedrocketry:machineScrubberActive").setCreativeTab(tabAdvRocketry).setBlockName("scrubber").setHardness(3f); AdvancedRocketryBlocks.blockUnlitTorch = new BlockTorchUnlit().setHardness(0.0F).setBlockName("unlittorch").setBlockTextureName("minecraft:torch_on"); AdvancedRocketryBlocks.blockVitrifiedSand = new BlockGeneric(Material.sand).setBlockName("vitrifiedSand").setCreativeTab(CreativeTabs.tabBlock).setBlockTextureName("advancedrocketry:vitrifiedSand").setHardness(0.5F).setStepSound(Block.soundTypeSand); AdvancedRocketryBlocks.blockCharcoalLog = new BlockCharcoalLog().setBlockName("charcoallog").setCreativeTab(CreativeTabs.tabBlock); AdvancedRocketryBlocks.blockElectricMushroom = new BlockElectricMushroom().setBlockName("electricMushroom").setCreativeTab(tabAdvRocketry).setBlockTextureName("advancedrocketry:mushroom_electric").setHardness(0.0F).setStepSound(Block.soundTypeGrass); AdvancedRocketryBlocks.blockCrystal = new BlockCrystal().setBlockName("crystal").setCreativeTab(LibVulpes.tabLibVulpesOres).setBlockTextureName("advancedrocketry:crystal").setHardness(2f); AdvancedRocketryBlocks.blockOrientationController = new BlockTile(TileStationOrientationControl.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber").setCreativeTab(tabAdvRocketry).setBlockName("orientationControl").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockOrientationController).setSideTexture("advancedrocketry:machineOrientationControl"); ((BlockTile) AdvancedRocketryBlocks.blockOrientationController).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockOrientationController).setFrontTexture("advancedrocketry:machineOrientationControl"); AdvancedRocketryBlocks.blockGravityController = new BlockTile(TileStationGravityController.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber").setCreativeTab(tabAdvRocketry).setBlockName("gravityControl").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockGravityController).setSideTexture("advancedrocketry:machineOrientationControl"); ((BlockTile) AdvancedRocketryBlocks.blockGravityController).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockGravityController).setFrontTexture("advancedrocketry:machineOrientationControl"); AdvancedRocketryBlocks.blockAltitudeController = new BlockTile(TileStationAltitudeController.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockTextureName("advancedrocketry:machineScrubber").setCreativeTab(tabAdvRocketry).setBlockName("alititudeController").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockAltitudeController).setSideTexture("advancedrocketry:machineOrientationControl"); ((BlockTile) AdvancedRocketryBlocks.blockAltitudeController).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockAltitudeController).setFrontTexture("advancedrocketry:machineOrientationControl"); AdvancedRocketryBlocks.blockOxygenCharger = new BlockTile(TileOxygenCharger.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("oxygenCharger").setCreativeTab(tabAdvRocketry).setBlockTextureName("libvulpes:machineGeneric").setHardness(3f); AdvancedRocketryBlocks.blockOxygenCharger.setBlockBounds(0, 0, 0, 1, 0.5f, 1); ((BlockTile) AdvancedRocketryBlocks.blockOxygenCharger).setSideTexture("advancedrocketry:panelSide"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenCharger).setTopTexture("advancedrocketry:gasChargerTop"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenCharger).setFrontTexture("advancedrocketry:panelSide"); AdvancedRocketryBlocks.blockOxygenVent = new BlockTile(TileOxygenVent.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("oxygenVent").setCreativeTab(tabAdvRocketry).setBlockTextureName("libvulpes:machineGeneric").setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockOxygenVent).setSideTexture("advancedrocketry:machineVent"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenVent).setTopTexture("advancedrocketry:machineVent"); ((BlockTile) AdvancedRocketryBlocks.blockOxygenVent).setFrontTexture("advancedrocketry:machineVent"); AdvancedRocketryBlocks.blockRocketBuilder = new BlockTile(TileRocketBuilder.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("rocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockRocketBuilder).setSideTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockRocketBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockRocketBuilder).setFrontTexture("advancedrocketry:MonitorFront"); AdvancedRocketryBlocks.blockDeployableRocketBuilder = new BlockTile(TileStationDeployedAssembler.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("deployableRocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockDeployableRocketBuilder).setSideTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockDeployableRocketBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockDeployableRocketBuilder).setFrontTexture("advancedrocketry:MonitorFront"); AdvancedRocketryBlocks.blockStationBuilder = new BlockTile(TileStationBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("stationAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockStationBuilder).setSideTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockStationBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockStationBuilder).setFrontTexture("advancedrocketry:MonitorFront"); AdvancedRocketryBlocks.blockFuelingStation = new BlockTileRedstoneEmitter(TileEntityFuelingStation.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("fuelStation").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockFuelingStation).setSideTexture("Advancedrocketry:FuelingMachine"); ((BlockTile) AdvancedRocketryBlocks.blockFuelingStation).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockFuelingStation).setFrontTexture("Advancedrocketry:FuelingMachine"); AdvancedRocketryBlocks.blockMonitoringStation = new BlockTileNeighborUpdate(TileEntityMoniteringStation.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockMonitoringStation).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockMonitoringStation).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockMonitoringStation).setFrontTexture("Advancedrocketry:MonitorRocket"); AdvancedRocketryBlocks.blockMonitoringStation.setBlockName("monitoringstation"); AdvancedRocketryBlocks.blockWarpShipMonitor = new BlockWarpShipMonitor(TileWarpShipMonitor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockWarpShipMonitor).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockWarpShipMonitor).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockWarpShipMonitor).setFrontTexture("Advancedrocketry:starshipcontrolPanel"); AdvancedRocketryBlocks.blockWarpShipMonitor.setBlockName("stationmonitor"); AdvancedRocketryBlocks.blockSatelliteBuilder = new BlockMultiblockMachine(TileSatelliteBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteBuilder).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteBuilder).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteBuilder).setFrontTexture("Advancedrocketry:satelliteAssembler"); AdvancedRocketryBlocks.blockSatelliteBuilder.setBlockName("satelliteBuilder"); AdvancedRocketryBlocks.blockSatelliteControlCenter = new BlockTile(TileEntitySatelliteControlCenter.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteControlCenter).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteControlCenter).setTopTexture("libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockSatelliteControlCenter).setFrontTexture("Advancedrocketry:MonitorSatellite"); AdvancedRocketryBlocks.blockSatelliteControlCenter.setBlockName("satelliteMonitor"); AdvancedRocketryBlocks.blockMicrowaveReciever = new BlockMultiblockMachine(TileMicrowaveReciever.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile) AdvancedRocketryBlocks.blockMicrowaveReciever).setSideTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile) AdvancedRocketryBlocks.blockMicrowaveReciever).setTopTexture("Advancedrocketry:solar"); ((BlockTile) AdvancedRocketryBlocks.blockMicrowaveReciever).setFrontTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockMicrowaveReciever.setBlockName("microwaveReciever"); //Arcfurnace AdvancedRocketryBlocks.blockArcFurnace = new BlockMultiblockMachine(TileElectricArcFurnace.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("electricArcFurnace").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockArcFurnace).setSideTexture("Advancedrocketry:BlastBrick"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockArcFurnace).setFrontTexture("Advancedrocketry:BlastBrickFront", "Advancedrocketry:BlastBrickFrontActive"); AdvancedRocketryBlocks.blockMoonTurf = new BlockPlanetSoil().setMapColor(MapColor.snowColor).setHardness(0.5F).setStepSound(Block.soundTypeGravel).setBlockName("turf").setBlockTextureName("advancedrocketry:moon_turf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockHotTurf = new BlockPlanetSoil().setMapColor(MapColor.netherrackColor).setHardness(0.5F).setStepSound(Block.soundTypeGravel).setBlockName("hotDryturf").setBlockTextureName("advancedrocketry:hotdry_turf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockLoader = new BlockARHatch(Material.rock).setBlockName("loader").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienWood = new BlockAlienWood().setBlockName("log").setBlockTextureName("advancedrocketry:log").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienLeaves = new BlockAlienLeaves().setBlockName("leaves2").setBlockTextureName("leaves").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienSapling = new BlockAlienSapling().setBlockName("sapling").setBlockTextureName("advancedrocketry:sapling").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockLightSource = new BlockLightSource(); AdvancedRocketryBlocks.blockBlastBrick = new BlockMultiBlockComponentVisible(Material.rock).setCreativeTab(tabAdvRocketry).setBlockName("blastBrick").setBlockTextureName("advancedRocketry:BlastBrick").setHardness(3F).setResistance(15F); AdvancedRocketryBlocks.blockQuartzCrucible = new BlockQuartzCrucible(); AdvancedRocketryBlocks.blockPrecisionAssembler = new BlockMultiblockMachine(TilePrecisionAssembler.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("precisionAssemblingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPrecisionAssembler).setFrontTexture("advancedrocketry:PrecisionAssemblerFront", "advancedrocketry:PrecisionAssemblerFront_Active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPrecisionAssembler).setSideTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockCuttingMachine = new BlockMultiblockMachine(TileCuttingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("cuttingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCuttingMachine).setFrontTexture("advancedrocketry:CuttingMachine", "advancedrocketry:CuttingMachine_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCuttingMachine).setSideTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockCrystallizer = new BlockMultiblockMachine(TileCrystallizer.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("Crystallizer").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCrystallizer).setSideTexture("Advancedrocketry:Crystallizer", "Advancedrocketry:Crystallizer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockCrystallizer).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockWarpCore = new BlockWarpCore(TileWarpCore.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("warpCore").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockWarpCore).setSideTexture("Advancedrocketry:warpcore"); AdvancedRocketryBlocks.blockChemicalReactor = new BlockMultiblockMachine(TileChemicalReactor.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("chemreactor").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockChemicalReactor).setFrontTexture("Advancedrocketry:Crystallizer", "Advancedrocketry:Crystallizer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockChemicalReactor).setTopTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockChemicalReactor).setSideTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockLathe = new BlockMultiblockMachine(TileLathe.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("lathe").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockLathe).setFrontTexture("Advancedrocketry:controlPanel"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockLathe).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockLathe).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockRollingMachine = new BlockMultiblockMachine(TileRollingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("rollingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockRollingMachine).setFrontTexture("Advancedrocketry:controlPanel"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockRollingMachine).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockRollingMachine).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockElectrolyser = new BlockMultiblockMachine(TileElectrolyser.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("electrolyser").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockElectrolyser).setFrontTexture("Advancedrocketry:machineElectrolzyer", "Advancedrocketry:machineElectrolzyer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockElectrolyser).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockElectrolyser).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockAtmosphereTerraformer = new BlockMultiblockMachine(TileAtmosphereTerraformer.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("atmosphereTerraformer").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockAtmosphereTerraformer).setFrontTexture("Advancedrocketry:machineElectrolzyer", "Advancedrocketry:machineElectrolzyer_active"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockAtmosphereTerraformer).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockAtmosphereTerraformer).setTopTexture("libvulpes:machineGeneric"); AdvancedRocketryBlocks.blockPlanetAnalyser = new BlockMultiblockMachine(TilePlanetAnalyser.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("planetanalyser").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPlanetAnalyser).setTopTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPlanetAnalyser).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockPlanetAnalyser).setFrontTexture("advancedrocketry:MonitorPlanet","advancedrocketry:MonitorPlanet_active"); AdvancedRocketryBlocks.blockObservatory = (BlockMultiblockMachine) new BlockMultiblockMachine(TileObservatory.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("observatory").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockObservatory).setTopTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockObservatory).setSideTexture("libvulpes:machineGeneric"); ((BlockMultiblockMachine) AdvancedRocketryBlocks.blockObservatory).setFrontTexture("advancedrocketry:MonitorFrontMid","advancedrocketry:MonitorFrontMid"); AdvancedRocketryBlocks.blockGuidanceComputer = new BlockTile(TileGuidanceComputer.class,GuiHandler.guiId.MODULAR.ordinal()).setBlockName("guidanceComputer").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockGuidanceComputer).setTopTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile)AdvancedRocketryBlocks.blockGuidanceComputer).setSideTexture("Advancedrocketry:MonitorSide"); ((BlockTile)AdvancedRocketryBlocks.blockGuidanceComputer).setFrontTexture("Advancedrocketry:guidanceComputer"); AdvancedRocketryBlocks.blockPlanetSelector = new BlockTile(TilePlanetSelector.class,GuiHandler.guiId.MODULARFULLSCREEN.ordinal()).setBlockName("planetSelector").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockPlanetSelector).setTopTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile)AdvancedRocketryBlocks.blockPlanetSelector).setSideTexture("Advancedrocketry:MonitorSide"); ((BlockTile)AdvancedRocketryBlocks.blockPlanetSelector).setFrontTexture("Advancedrocketry:guidanceComputer"); AdvancedRocketryBlocks.blockBiomeScanner = new BlockMultiblockMachine(TileBiomeScanner.class,GuiHandler.guiId.MODULARNOINV.ordinal()).setBlockName("biomeScanner").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockBiomeScanner).setTopTexture("libvulpes:machineGeneric", "libvulpes:machineGeneric"); ((BlockTile)AdvancedRocketryBlocks.blockBiomeScanner).setSideTexture("Advancedrocketry:MonitorSide"); ((BlockTile)AdvancedRocketryBlocks.blockBiomeScanner).setFrontTexture("Advancedrocketry:guidanceComputer"); AdvancedRocketryBlocks.blockDrill = new BlockMiningDrill().setBlockName("drill").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockDrill).setTopTexture("Advancedrocketry:laserBottom", "Advancedrocketry:laserBottom"); ((BlockTile)AdvancedRocketryBlocks.blockDrill).setSideTexture("Advancedrocketry:machineWarning"); ((BlockTile)AdvancedRocketryBlocks.blockDrill).setFrontTexture("Advancedrocketry:machineWarning"); AdvancedRocketryBlocks.blockSuitWorkStation = new BlockTile(TileSuitWorkStation.class, GuiHandler.guiId.MODULAR.ordinal()).setBlockName("suitWorkStation").setCreativeTab(tabAdvRocketry).setHardness(3f); ((BlockTile)AdvancedRocketryBlocks.blockSuitWorkStation).setTopTexture("Advancedrocketry:suitWorkStation"); ((BlockTile)AdvancedRocketryBlocks.blockSuitWorkStation).setSideTexture("Advancedrocketry:panelSideWorkStation"); ((BlockTile)AdvancedRocketryBlocks.blockSuitWorkStation).setFrontTexture("Advancedrocketry:panelSideWorkStation"); AdvancedRocketryBlocks.blockDockingPort = new BlockStationModuleDockingPort(Material.iron).setBlockName("stationMarker").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarGenerator = new BlockTile(TileSolarPanel.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f).setBlockName("solarGenerator"); ((BlockTile)AdvancedRocketryBlocks.blockSolarGenerator).setTopTexture("Advancedrocketry:solar"); ((BlockTile)AdvancedRocketryBlocks.blockSolarGenerator).setSideTexture("Advancedrocketry:panelSide"); ((BlockTile)AdvancedRocketryBlocks.blockSolarGenerator).setFrontTexture("Advancedrocketry:panelSide"); ((BlockTile)AdvancedRocketryBlocks.blockSolarGenerator).setBottomTexture("Advancedrocketry:qcrucible_inner"); AdvancedRocketryBlocks.blockIntake = new BlockIntake(Material.iron).setBlockTextureName("advancedrocketry:intake").setBlockName("gasIntake").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPressureTank = new BlockPressurizedFluidTank(Material.iron).setBlockName("pressurizedTank").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarPanel = new BlockSolarPanel(Material.iron).setBlockName("solarPanel").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCircularLight = new BlockGeneric(Material.iron).setBlockName("circleLight").setCreativeTab(tabAdvRocketry).setHardness(2f).setBlockTextureName("advancedrocketry:stationLight").setLightLevel(1f); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { AdvancedRocketryBlocks.blockSpaceLaser = new BlockLaser(); AdvancedRocketryBlocks.blockSpaceLaser.setCreativeTab(tabAdvRocketry); } //Fluid Registration AdvancedRocketryFluids.fluidOxygen = new FluidColored("oxygen",0x8f94b9).setUnlocalizedName("oxygen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidOxygen)) { AdvancedRocketryFluids.fluidOxygen = FluidRegistry.getFluid("oxygen"); } AdvancedRocketryFluids.fluidHydrogen = new FluidColored("hydrogen",0xdbc1c1).setUnlocalizedName("hydrogen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidHydrogen)) { AdvancedRocketryFluids.fluidHydrogen = FluidRegistry.getFluid("hydrogen"); } AdvancedRocketryFluids.fluidRocketFuel = new FluidColored("rocketFuel", 0xe5d884).setUnlocalizedName("rocketFuel").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidRocketFuel)) { AdvancedRocketryFluids.fluidRocketFuel = FluidRegistry.getFluid("rocketFuel"); } AdvancedRocketryFluids.fluidNitrogen = new FluidColored("nitrogen", 0x97a7e7); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidNitrogen)) { AdvancedRocketryFluids.fluidNitrogen = FluidRegistry.getFluid("nitrogen"); } AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidNitrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidHydrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidOxygen); AdvancedRocketryBlocks.blockOxygenFluid = new BlockFluid(AdvancedRocketryFluids.fluidOxygen, Material.water).setBlockName("oxygenFluidBlock").setCreativeTab(CreativeTabs.tabMisc); AdvancedRocketryBlocks.blockHydrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidHydrogen, Material.water).setBlockName("hydrogenFluidBlock").setCreativeTab(CreativeTabs.tabMisc); AdvancedRocketryBlocks.blockFuelFluid = new BlockFluid(AdvancedRocketryFluids.fluidRocketFuel, Material.water).setBlockName("rocketFuelBlock").setCreativeTab(CreativeTabs.tabMisc); AdvancedRocketryBlocks.blockNitrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidNitrogen, Material.water).setBlockName("nitrogenFluidBlock").setCreativeTab(CreativeTabs.tabMisc); //Cables //AdvancedRocketryBlocks.blockFluidPipe = new BlockLiquidPipe(Material.iron).setBlockName("liquidPipe").setCreativeTab(CreativeTabs.tabTransport); AdvancedRocketryBlocks.blockDataPipe = new BlockDataCable(Material.iron).setBlockName("dataPipe").setCreativeTab(tabAdvRocketry).setBlockTextureName("AdvancedRocketry:pipeData"); AdvancedRocketryBlocks.blockFluidPipe = new BlockLiquidPipe(Material.iron).setBlockName("liquidPipe").setCreativeTab(tabAdvRocketry).setBlockTextureName("AdvancedRocketry:pipeLiquid"); AdvancedRocketryBlocks.blockEnergyPipe = new BlockEnergyPipe(Material.iron).setBlockName("energyPipe").setCreativeTab(tabAdvRocketry).setBlockTextureName("AdvancedRocketry:pipeEnergy");; GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDataPipe , AdvancedRocketryBlocks.blockDataPipe .getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFluidPipe , AdvancedRocketryBlocks.blockFluidPipe .getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockEnergyPipe , AdvancedRocketryBlocks.blockEnergyPipe.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLaunchpad, "launchpad"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockRocketBuilder, "rocketBuilder"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockStructureTower, "structureTower"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockGenericSeat, "seat"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockEngine, "rocketmotor"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFuelTank, "fuelTank"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFuelingStation, "fuelingStation"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMonitoringStation, "blockMonitoringStation"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSatelliteBuilder, "blockSatelliteBuilder"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMoonTurf, "moonTurf"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockHotTurf, "blockHotTurf"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLoader, ItemBlockMeta.class, AdvancedRocketryBlocks.blockLoader.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPrecisionAssembler, "precisionassemblingmachine"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockBlastBrick, "utilBlock"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockQuartzCrucible, "quartzcrucible"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCrystallizer, "crystallizer"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCuttingMachine, "cuttingMachine"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAlienWood, "alienWood"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAlienLeaves, "alienLeaves"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAlienSapling, "alienSapling"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockObservatory, "observatory"); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockConcrete, AdvancedRocketryBlocks.blockConcrete.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPlanetSelector, AdvancedRocketryBlocks.blockPlanetSelector.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSatelliteControlCenter, AdvancedRocketryBlocks.blockSatelliteControlCenter.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPlanetAnalyser, AdvancedRocketryBlocks.blockPlanetAnalyser.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockGuidanceComputer, AdvancedRocketryBlocks.blockGuidanceComputer.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockArcFurnace, AdvancedRocketryBlocks.blockArcFurnace.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSawBlade, AdvancedRocketryBlocks.blockSawBlade.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMotor, AdvancedRocketryBlocks.blockMotor.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLathe, AdvancedRocketryBlocks.blockLathe.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockRollingMachine, AdvancedRocketryBlocks.blockRollingMachine.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPlatePress, AdvancedRocketryBlocks.blockPlatePress .getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockStationBuilder, AdvancedRocketryBlocks.blockStationBuilder.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockElectrolyser, AdvancedRocketryBlocks.blockElectrolyser.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockChemicalReactor, AdvancedRocketryBlocks.blockChemicalReactor.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenScrubber, AdvancedRocketryBlocks.blockOxygenScrubber.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenVent, AdvancedRocketryBlocks.blockOxygenVent.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenCharger, AdvancedRocketryBlocks.blockOxygenCharger.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAirLock, AdvancedRocketryBlocks.blockAirLock.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLandingPad, AdvancedRocketryBlocks.blockLandingPad.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockWarpCore, AdvancedRocketryBlocks.blockWarpCore.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockWarpShipMonitor, AdvancedRocketryBlocks.blockWarpShipMonitor.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenDetection, AdvancedRocketryBlocks.blockOxygenDetection.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockUnlitTorch, AdvancedRocketryBlocks.blockUnlitTorch.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blocksGeode,AdvancedRocketryBlocks.blocksGeode.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOxygenFluid,ItemFluid.class, AdvancedRocketryBlocks.blockOxygenFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockHydrogenFluid,ItemFluid.class, AdvancedRocketryBlocks.blockHydrogenFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockFuelFluid, ItemFluid.class, AdvancedRocketryBlocks.blockFuelFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockNitrogenFluid, ItemFluid.class, AdvancedRocketryBlocks.blockNitrogenFluid.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockVitrifiedSand, AdvancedRocketryBlocks.blockVitrifiedSand.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCharcoalLog, AdvancedRocketryBlocks.blockCharcoalLog.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockElectricMushroom, AdvancedRocketryBlocks.blockElectricMushroom.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCrystal, ItemCrystalBlock.class, AdvancedRocketryBlocks.blockCrystal.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockOrientationController, AdvancedRocketryBlocks.blockOrientationController.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockGravityController, AdvancedRocketryBlocks.blockGravityController.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDrill, AdvancedRocketryBlocks.blockDrill.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockMicrowaveReciever, AdvancedRocketryBlocks.blockMicrowaveReciever.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockLightSource, AdvancedRocketryBlocks.blockLightSource.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSolarPanel, AdvancedRocketryBlocks.blockSolarPanel.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSuitWorkStation, AdvancedRocketryBlocks.blockSuitWorkStation.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockBiomeScanner, AdvancedRocketryBlocks.blockBiomeScanner.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAtmosphereTerraformer, AdvancedRocketryBlocks.blockAtmosphereTerraformer.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDeployableRocketBuilder, AdvancedRocketryBlocks.blockDeployableRocketBuilder.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockPressureTank, AdvancedRocketryBlocks.blockPressureTank.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockIntake, AdvancedRocketryBlocks.blockIntake.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockCircularLight, AdvancedRocketryBlocks.blockCircularLight.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockDockingPort, AdvancedRocketryBlocks.blockDockingPort.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSolarGenerator, AdvancedRocketryBlocks.blockSolarGenerator.getUnlocalizedName()); GameRegistry.registerBlock(AdvancedRocketryBlocks.blockAltitudeController, AdvancedRocketryBlocks.blockAltitudeController.getUnlocalizedName()); //TODO, use different mechanism to enable/disable drill if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) GameRegistry.registerBlock(AdvancedRocketryBlocks.blockSpaceLaser, "laserController"); AdvancedRocketryItems.itemWafer = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:wafer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCircuitPlate = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:circuitplate").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemIC = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:circuitIC").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemMisc = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:miscpart").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSawBlade = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:sawBlade").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStationChip = new ItemStationChip().setUnlocalizedName("stationChip").setTextureName("advancedRocketry:stationIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemAsteroidChip = new ItemAsteroidChip().setUnlocalizedName("asteroidChip").setTextureName("advancedRocketry:stationIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStation = new ItemPackedStructure().setUnlocalizedName("station").setTextureName("advancedRocketry:SpaceStation"); AdvancedRocketryItems.itemSmallAirlockDoor = new ItemDoor2(Material.rock).setUnlocalizedName("smallAirlock").setTextureName("advancedRocketry:smallAirlock").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCarbonScrubberCartridge = new Item().setMaxDamage(172800).setUnlocalizedName("carbonScrubberCartridge").setTextureName("advancedRocketry:carbonCartridge").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemLens = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:lens").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePowerSource = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:satellitePowerSource").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePrimaryFunction = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:satellitePrimaryFunction").setCreativeTab(tabAdvRocketry); //TODO: move registration in the case we have more than one chip type AdvancedRocketryItems.itemDataUnit = new ItemData().setUnlocalizedName("advancedrocketry:dataUnit").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemOreScanner = new ItemOreScanner().setUnlocalizedName("OreScanner").setTextureName("advancedRocketry:oreScanner").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemQuartzCrucible = (new ItemBlockWithIcon(AdvancedRocketryBlocks.blockQuartzCrucible)).setUnlocalizedName("qcrucible").setCreativeTab(tabAdvRocketry).setTextureName("advancedRocketry:qcrucible"); AdvancedRocketryItems.itemSatellite = new ItemSatellite().setUnlocalizedName("satellite").setTextureName("advancedRocketry:satellite"); AdvancedRocketryItems.itemSatelliteIdChip = new ItemSatelliteIdentificationChip().setUnlocalizedName("satelliteIdChip").setTextureName("advancedRocketry:satelliteIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemPlanetIdChip = new ItemPlanetIdentificationChip().setUnlocalizedName("planetIdChip").setTextureName("advancedRocketry:planetIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemBiomeChanger = new ItemBiomeChanger().setUnlocalizedName("biomeChanger").setTextureName("advancedrocketry:biomeChanger").setCreativeTab(tabAdvRocketry); //Fluids AdvancedRocketryItems.itemBucketRocketFuel = new ItemBucket(AdvancedRocketryBlocks.blockFuelFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketRocketFuel").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); AdvancedRocketryItems.itemBucketNitrogen = new ItemBucket(AdvancedRocketryBlocks.blockNitrogenFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketNitrogen").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); AdvancedRocketryItems.itemBucketHydrogen = new ItemBucket(AdvancedRocketryBlocks.blockHydrogenFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketHydrogen").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); AdvancedRocketryItems.itemBucketOxygen = new ItemBucket(AdvancedRocketryBlocks.blockOxygenFluid).setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketOxygen").setTextureName("advancedRocketry:bucket_liquid").setContainerItem(Items.bucket); //Suit Component Registration AdvancedRocketryItems.itemJetpack = new ItemJetpack().setCreativeTab(tabAdvRocketry).setUnlocalizedName("jetPack").setTextureName("advancedRocketry:jetpack"); AdvancedRocketryItems.itemPressureTank = new ItemPressureTank(4, 1000).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:pressureTank").setTextureName("advancedRocketry:pressureTank"); AdvancedRocketryItems.itemUpgrade = new ItemUpgrade(5).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:itemUpgrade").setTextureName("advancedRocketry:itemUpgrade"); AdvancedRocketryItems.itemAtmAnalyser = new ItemAtmosphereAnalzer().setCreativeTab(tabAdvRocketry).setUnlocalizedName("atmAnalyser").setTextureName("advancedRocketry:atmosphereAnalyzer"); //Armor registration AdvancedRocketryItems.itemSpaceSuit_Helmet = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 0).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceHelmet").setTextureName("advancedRocketry:space_helmet"); AdvancedRocketryItems.itemSpaceSuit_Chest = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceChest").setTextureName("advancedRocketry:space_chestplate"); AdvancedRocketryItems.itemSpaceSuit_Leggings = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 2).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceLeggings").setTextureName("advancedRocketry:space_leggings"); AdvancedRocketryItems.itemSpaceSuit_Boots = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, 3).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceBoots").setTextureName("advancedRocketry:space_boots"); AdvancedRocketryItems.itemSealDetector = new ItemSealDetector().setMaxStackSize(1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sealDetector").setTextureName("advancedRocketry:seal_detector"); //Tools AdvancedRocketryItems.itemJackhammer = new ItemJackHammer(ToolMaterial.EMERALD).setTextureName("advancedRocketry:jackHammer").setUnlocalizedName("jackhammer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("jackhammer", 3); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("pickaxe", 3); //Register Satellite Properties SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOptical.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteComposition.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteMassScanner.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteEnergy.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOreMapping.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteBiomeChanger.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), new SatelliteProperties().setPowerGeneration(1)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1), new SatelliteProperties().setPowerGeneration(10)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 0), new SatelliteProperties().setPowerStorage(100)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 1), new SatelliteProperties().setPowerStorage(400)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), new SatelliteProperties().setMaxData(1000)); //Item Registration GameRegistry.registerItem(AdvancedRocketryItems.itemQuartzCrucible, "iquartzcrucible"); GameRegistry.registerItem(AdvancedRocketryItems.itemOreScanner, "oreScanner"); GameRegistry.registerItem(AdvancedRocketryItems.itemSatellitePowerSource, AdvancedRocketryItems.itemSatellitePowerSource.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSatellitePrimaryFunction, AdvancedRocketryItems.itemSatellitePrimaryFunction.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemCircuitPlate, AdvancedRocketryItems.itemCircuitPlate.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemIC, AdvancedRocketryItems.itemIC.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemWafer, AdvancedRocketryItems.itemWafer.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemDataUnit, AdvancedRocketryItems.itemDataUnit.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSatellite, AdvancedRocketryItems.itemSatellite.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSatelliteIdChip, AdvancedRocketryItems.itemSatelliteIdChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemPlanetIdChip,AdvancedRocketryItems.itemPlanetIdChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemMisc, AdvancedRocketryItems.itemMisc.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSawBlade, AdvancedRocketryItems.itemSawBlade.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceStationChip, AdvancedRocketryItems.itemSpaceStationChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceStation, AdvancedRocketryItems.itemSpaceStation.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Helmet, AdvancedRocketryItems.itemSpaceSuit_Helmet.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Boots, AdvancedRocketryItems.itemSpaceSuit_Boots.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Chest, AdvancedRocketryItems.itemSpaceSuit_Chest.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSpaceSuit_Leggings, AdvancedRocketryItems.itemSpaceSuit_Leggings.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketRocketFuel, AdvancedRocketryItems.itemBucketRocketFuel.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketNitrogen, AdvancedRocketryItems.itemBucketNitrogen.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketHydrogen, AdvancedRocketryItems.itemBucketHydrogen.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemBucketOxygen, AdvancedRocketryItems.itemBucketOxygen.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSmallAirlockDoor, AdvancedRocketryItems.itemSmallAirlockDoor.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemCarbonScrubberCartridge, AdvancedRocketryItems.itemCarbonScrubberCartridge.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemSealDetector, AdvancedRocketryItems.itemSealDetector.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemJackhammer, AdvancedRocketryItems.itemJackhammer.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemAsteroidChip, AdvancedRocketryItems.itemAsteroidChip.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemLens, AdvancedRocketryItems.itemLens.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemJetpack, AdvancedRocketryItems.itemJetpack.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemPressureTank, AdvancedRocketryItems.itemPressureTank.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemUpgrade, AdvancedRocketryItems.itemUpgrade.getUnlocalizedName()); GameRegistry.registerItem(AdvancedRocketryItems.itemAtmAnalyser, AdvancedRocketryItems.itemAtmAnalyser.getUnlocalizedName()); if(zmaster587.advancedRocketry.api.Configuration.enableTerraforming) GameRegistry.registerItem(AdvancedRocketryItems.itemBiomeChanger, AdvancedRocketryItems.itemBiomeChanger.getUnlocalizedName()); //End Items EntityRegistry.registerModEntity(EntityDummy.class, "mountDummy", 0, this, 16, 20, false); EntityRegistry.registerModEntity(EntityRocket.class, "rocket", 1, this, 64, 3, true); EntityRegistry.registerModEntity(EntityLaserNode.class, "laserNode", 2, instance, 256, 20, false); EntityRegistry.registerModEntity(EntityStationDeployedRocket.class, "deployedRocket", 3, this, 256, 600, true); GameRegistry.registerTileEntity(TileRocketBuilder.class, "ARrocketBuilder"); GameRegistry.registerTileEntity(TileWarpCore.class, "ARwarpCore"); GameRegistry.registerTileEntity(TileModelRender.class, "ARmodelRenderer"); GameRegistry.registerTileEntity(TileEntityFuelingStation.class, "ARfuelingStation"); GameRegistry.registerTileEntity(TileEntityMoniteringStation.class, "ARmonitoringStation"); GameRegistry.registerTileEntity(TileMissionController.class, "ARmissionControlComp"); GameRegistry.registerTileEntity(TileSpaceLaser.class, "ARspaceLaser"); GameRegistry.registerTileEntity(TilePrecisionAssembler.class, "ARprecisionAssembler"); GameRegistry.registerTileEntity(TileObservatory.class, "ARobservatory"); GameRegistry.registerTileEntity(TileCrystallizer.class, "ARcrystallizer"); GameRegistry.registerTileEntity(TileCuttingMachine.class, "ARcuttingmachine"); GameRegistry.registerTileEntity(TileDataBus.class, "ARdataBus"); GameRegistry.registerTileEntity(TileEnergyPipe.class, "AREnergyPipe"); GameRegistry.registerTileEntity(TileLiquidPipe.class, "ARLiquidPipe"); GameRegistry.registerTileEntity(TileSatelliteHatch.class, "ARsatelliteHatch"); GameRegistry.registerTileEntity(TileSatelliteBuilder.class, "ARsatelliteBuilder"); GameRegistry.registerTileEntity(TileEntitySatelliteControlCenter.class, "ARTileEntitySatelliteControlCenter"); GameRegistry.registerTileEntity(TilePlanetAnalyser.class, "ARplanetAnalyser"); GameRegistry.registerTileEntity(TileGuidanceComputer.class, "ARguidanceComputer"); GameRegistry.registerTileEntity(TileElectricArcFurnace.class, "ARelectricArcFurnace"); GameRegistry.registerTileEntity(TilePlanetSelector.class, "ARTilePlanetSelector"); GameRegistry.registerTileEntity(TileModelRenderRotatable.class, "ARTileModelRenderRotatable"); GameRegistry.registerTileEntity(TileMaterial.class, "ARTileMaterial"); GameRegistry.registerTileEntity(TileLathe.class, "ARTileLathe"); GameRegistry.registerTileEntity(TileRollingMachine.class, "ARTileMetalBender"); GameRegistry.registerTileEntity(TileStationBuilder.class, "ARStationBuilder"); GameRegistry.registerTileEntity(TileElectrolyser.class, "ARElectrolyser"); GameRegistry.registerTileEntity(TileChemicalReactor.class, "ARChemicalReactor"); GameRegistry.registerTileEntity(TileOxygenVent.class, "AROxygenVent"); GameRegistry.registerTileEntity(TileOxygenCharger.class, "AROxygenCharger"); GameRegistry.registerTileEntity(TileCO2Scrubber.class, "ARCO2Scrubber"); GameRegistry.registerTileEntity(TileWarpShipMonitor.class, "ARStationMonitor"); GameRegistry.registerTileEntity(TileAtmosphereDetector.class, "AROxygenDetector"); GameRegistry.registerTileEntity(TileStationOrientationControl.class, "AROrientationControl"); GameRegistry.registerTileEntity(TileStationGravityController.class, "ARGravityControl"); GameRegistry.registerTileEntity(TileDataPipe.class, "ARDataPipe"); GameRegistry.registerTileEntity(TileDrill.class, "ARDrill"); GameRegistry.registerTileEntity(TileMicrowaveReciever.class, "ARMicrowaveReciever"); GameRegistry.registerTileEntity(TileSuitWorkStation.class, "ARSuitWorkStation"); GameRegistry.registerTileEntity(TileRocketLoader.class, "ARRocketLoader"); GameRegistry.registerTileEntity(TileRocketUnloader.class, "ARRocketUnloader"); GameRegistry.registerTileEntity(TileBiomeScanner.class, "ARBiomeScanner"); GameRegistry.registerTileEntity(TileAtmosphereTerraformer.class, "ARAttTerraformer"); GameRegistry.registerTileEntity(TileLandingPad.class, "ARLandingPad"); GameRegistry.registerTileEntity(TileStationDeployedAssembler.class, "ARStationDeployableRocketAssembler"); GameRegistry.registerTileEntity(TileFluidTank.class, "ARFluidTank"); GameRegistry.registerTileEntity(TileRocketFluidUnloader.class, "ARFluidUnloader"); GameRegistry.registerTileEntity(TileRocketFluidLoader.class, "ARFluidLoader"); GameRegistry.registerTileEntity(TileDockingPort.class, "ARDockingPort"); GameRegistry.registerTileEntity(TileSolarPanel.class, "ARSolarGenerator"); GameRegistry.registerTileEntity(TileStationAltitudeController.class, "ARAltitudeController"); //OreDict stuff OreDictionary.registerOre("waferSilicon", new ItemStack(AdvancedRocketryItems.itemWafer,1,0)); OreDictionary.registerOre("ingotCartileEntityClassbon", new ItemStack(AdvancedRocketryItems.itemMisc, 1, 1)); OreDictionary.registerOre("concrete", new ItemStack(AdvancedRocketryBlocks.blockConcrete)); //Register machine recipes LibVulpes.registerRecipeHandler(TileCuttingMachine.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/CuttingMachine.xml"); LibVulpes.registerRecipeHandler(TilePrecisionAssembler.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/PrecisionAssembler.xml"); LibVulpes.registerRecipeHandler(TileChemicalReactor.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/ChemicalReactor.xml"); LibVulpes.registerRecipeHandler(TileCrystallizer.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Crystallizer.xml"); LibVulpes.registerRecipeHandler(TileElectrolyser.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Electrolyser.xml"); LibVulpes.registerRecipeHandler(TileElectricArcFurnace.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/ElectricArcFurnace.xml"); LibVulpes.registerRecipeHandler(TileLathe.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Lathe.xml"); LibVulpes.registerRecipeHandler(TileRollingMachine.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/RollingMachine.xml"); //Register Space Objects SpaceObjectManager.getSpaceManager().registerSpaceObjectType("genericObject", SpaceObject.class); //Register Allowed Products materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumAluminide", "pickaxe", 1, 0xaec2de, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false)); materialRegistry.registerOres(LibVulpes.tabLibVulpesOres, "advancedRocketry"); CompatibilityMgr.getLoadedMods(); } @EventHandler public void load(FMLInitializationEvent event) { zmaster587.advancedRocketry.cable.NetworkRegistry.registerFluidNetwork(); ItemStack userInterface = new ItemStack(AdvancedRocketryItems.itemMisc, 1,0); ItemStack basicCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,0); ItemStack advancedCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,2); ItemStack controlCircuitBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,3); ItemStack itemIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,4); ItemStack liquidIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,5); ItemStack trackingCircuit = new ItemStack(AdvancedRocketryItems.itemIC,1,1); ItemStack opticalSensor = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0); ItemStack biomeChanger = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5); ItemStack smallSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0); ItemStack largeSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1); ItemStack smallBattery = new ItemStack(LibVulpesItems.itemBattery,1,0); ItemStack battery2x = new ItemStack(LibVulpesItems.itemBattery,1,1); ItemStack superHighPressureTime = new ItemStack(AdvancedRocketryItems.itemPressureTank,1,3); //Register Alloys MaterialRegistry.registerMixedMaterial(new MixedMaterial(TileElectricArcFurnace.class, "oreRutile", new ItemStack[] {MaterialRegistry.getMaterialFromName("Titanium").getProduct(AllowedProducts.getProductByName("INGOT"))})); proxy.registerRenderers(); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockBlastBrick,16), new ItemStack(Items.potionitem,1,8195), new ItemStack(Items.potionitem,1,8201), Blocks.brick_block, Blocks.brick_block, Blocks.brick_block, Blocks.brick_block); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockArcFurnace), "aga","ice", "aba", 'a', Items.netherbrick, 'g', userInterface, 'i', itemIOBoard, 'e',controlCircuitBoard, 'c', AdvancedRocketryBlocks.blockBlastBrick, 'b', "ingotCopper")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemQuartzCrucible), " a ", "aba", " a ", Character.valueOf('a'), Items.quartz, Character.valueOf('b'), Items.cauldron); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockPlatePress, " ", " a ", "iii", 'a', Blocks.piston, 'i', Items.iron_ingot)); GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")), "x ", " x ", " x", 'x', "ingotIron")); GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Steel", AllowedProducts.getProductByName("STICK")), "x ", " x ", " x", 'x', "ingotSteel")); GameRegistry.addSmelting(MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("ORE")), MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("DUST")), 0); //Supporting Materials GameRegistry.addRecipe(new ShapedOreRecipe(userInterface, "lrl", "fgf", 'l', "dyeLime", 'r', Items.redstone, 'g', Blocks.glass_pane, 'f', Items.glowstone_dust)); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockGenericSeat), "xxx", 'x', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockConcrete), Blocks.sand, Blocks.gravel, Items.water_bucket); GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockLaunchpad, "concrete", "dyeBlack", "dyeYellow")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockStructureTower, "ooo", " o ", "ooo", 'o', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockEngine, "sss", " t ","t t", 's', "ingotSteel", 't', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockFuelTank, "s s", "p p", "s s", 'p', "plateSteel", 's', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(smallBattery, " c ","prp", "prp", 'c', "stickIron", 'r', Items.redstone, 'p', "plateTin")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemBattery,1,1), "bpb", "bpb", 'b', smallBattery, 'p', "plateCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), "ppp", " g ", " l ", 'p', Blocks.glass_pane, 'g', Items.glowstone_dust, 'l', "plateGold")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockObservatory), "gug", "pbp", "rrr", 'g', Blocks.glass_pane, 'u', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'r', MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK"))); //Hatches GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,0), "c", "m"," ", 'c', Blocks.chest, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,1), "m", "c"," ", 'c', Blocks.chest, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,2), "c", "m", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,3), "m", "c", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,0), "m", "c"," ", 'c', AdvancedRocketryItems.itemDataUnit, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,1), " x ", "xmx"," x ", 'x', "stickTitanium", 'm', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,2), new ItemStack(LibVulpesBlocks.blockHatch,1,1), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,3), new ItemStack(LibVulpesBlocks.blockHatch,1,0), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,4), new ItemStack(LibVulpesBlocks.blockHatch,1,3), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,5), new ItemStack(LibVulpesBlocks.blockHatch,1,2), trackingCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMotor), " cp", "rrp"," cp", 'c', "coilCopper", 'p', "plateSteel", 'r', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), "rrr", "ggg","ppp", 'r', Items.redstone, 'g', Items.glowstone_dust, 'p', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemHoloProjector), "oro", "rpr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'r', Items.redstone, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', "crystalDilithium")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemLens, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0), " x ","xox", " x ", 'x', "plateIron", 'o', "stickIron")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSawBlade,1,0), "r r","xox", "x x", 'r', "stickIron", 'x', "plateIron", 'o', new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0))); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSpaceStationChip), LibVulpesItems.itemLinker , basicCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge), "xix", "xix", "xix", 'x', "sheetIron", 'i', Blocks.iron_bars)); //Plugs GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockRFBattery), " x ", "xmx"," x ", 'x', LibVulpesItems.itemBattery, 'm', LibVulpesBlocks.blockStructureBlock); //O2 Support GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenVent), "bfb", "bmb", "btb", 'b', Blocks.iron_bars, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', AdvancedRocketryBlocks.blockFuelTank)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenScrubber), "bfb", "bmb", "btb", 'b', Blocks.iron_bars, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', "ingotCarbon")); //MACHINES GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPrecisionAssembler), "abc", "def", "ghi", 'a', Items.repeater, 'b', userInterface, 'c', Items.diamond, 'd', itemIOBoard, 'e', LibVulpesBlocks.blockStructureBlock, 'f', controlCircuitBoard, 'g', Blocks.furnace, 'h', "gearSteel", 'i', Blocks.dropper)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCrystallizer), "ada", "ecf","bgb", 'a', Items.quartz, 'b', Items.repeater, 'c', LibVulpesBlocks.blockStructureBlock, 'd', userInterface, 'e', itemIOBoard, 'f', controlCircuitBoard, 'g', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCuttingMachine), "aba", "cde", "opo", 'a', "gearSteel", 'b', userInterface, 'c', itemIOBoard, 'e', controlCircuitBoard, 'p', "plateSteel", 'o', Blocks.obsidian, 'd', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLathe), "rsr", "abc", "pgp", 'r', "stickIron",'a', itemIOBoard, 'c', controlCircuitBoard, 'g', "gearSteel", 'p', "plateSteel", 'b', LibVulpesBlocks.blockStructureBlock, 's', userInterface)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRollingMachine), "psp", "abc", "iti", 'a', itemIOBoard, 'c', controlCircuitBoard, 'p', "gearSteel", 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'i', "blockIron",'t', liquidIOBoard)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMonitoringStation), "coc", "cbc", "cpc", 'c', "stickCopper", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'b', LibVulpesBlocks.blockStructureBlock, 'p', LibVulpesItems.itemBattery)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFuelingStation), "bgb", "lbf", "ppp", 'p', "plateTin", 'f', "fanSteel", 'l', liquidIOBoard, 'g', AdvancedRocketryItems.itemMisc, 'x', AdvancedRocketryBlocks.blockFuelTank, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteControlCenter), "oso", "cbc", "rtr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 's', userInterface, 'c', "stickCopper", 'b', LibVulpesBlocks.blockStructureBlock, 'r', Items.repeater, 't', LibVulpesItems.itemBattery)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteBuilder), "dht", "cbc", "mas", 'd', AdvancedRocketryItems.itemDataUnit, 'h', Blocks.hopper, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'm', AdvancedRocketryBlocks.blockMotor, 'a', Blocks.anvil, 's', AdvancedRocketryBlocks.blockSawBlade, 't', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetAnalyser), "tst", "pbp", "cpc", 't', trackingCircuit, 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateTin", 'c', AdvancedRocketryItems.itemPlanetIdChip)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockGuidanceComputer), "ctc", "rbr", "crc", 'c', trackingCircuit, 't', "plateTitanium", 'r', Items.redstone, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetSelector), "cpc", "lbl", "coc", 'c', trackingCircuit, 'o',new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'l', Blocks.lever, 'b', AdvancedRocketryBlocks.blockGuidanceComputer, 'p', Blocks.stone_button)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder), "sgs", "cbc", "tdt", 's', "stickTitanium", 'g', AdvancedRocketryItems.itemMisc, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 't', "gearTitanium", 'd', AdvancedRocketryBlocks.blockConcrete)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockStationBuilder), "gdg", "dsd", "ada", 'g', "gearTitanium", 'a', advancedCircuit, 'd', "dustDilithium", 's', new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockElectrolyser), "pip", "abc", "ded", 'd', basicCircuit, 'p', "plateSteel", 'i', userInterface, 'a', liquidIOBoard, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'e', Blocks.redstone_torch)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenCharger), "fif", "tbt", "pcp", 'p', "plateSteel", 'f', "fanSteel", 'c', Blocks.heavy_weighted_pressure_plate, 'i', AdvancedRocketryItems.itemMisc, 'b', LibVulpesBlocks.blockStructureBlock, 't', AdvancedRocketryBlocks.blockFuelTank)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockChemicalReactor), "pip", "abd", "rcr", 'a', itemIOBoard, 'd', controlCircuitBoard, 'r', basicCircuit, 'p', "plateGold", 'i', userInterface, 'c', liquidIOBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'g', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpCore), "gcg", "pbp", "gcg", 'p', "plateSteel", 'c', advancedCircuit, 'b', "coilCopper", 'g', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenDetection), "pip", "gbf", "pcp", 'p', "plateSteel",'f', "fanSteel", 'i', userInterface, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'g', Blocks.iron_bars)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpShipMonitor), "pip", "obo", "pcp", 'o', controlCircuitBoard, 'p', "plateSteel", 'i', userInterface, 'c', advancedCircuit, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockBiomeScanner), "plp", "bsb","ppp", 'p', "plateTin", 'l', biomeChanger, 'b', smallBattery, 's', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockDeployableRocketBuilder), "gdg", "dad", "rdr", 'g', "gearTitaniumAluminide", 'd', "dustDilithium", 'r', "stickTitaniumAluminide", 'a', AdvancedRocketryBlocks.blockRocketBuilder)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPressureTank), "tgt","tgt","tgt", 't', superHighPressureTime, 'g', Blocks.glass_pane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockIntake), "rhr", "hbh", "rhr", 'r', "stickTitanium", 'h', Blocks.hopper, 'b', LibVulpesBlocks.blockStructureBlock)); //Armor recipes GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Boots, " r ", "w w", "p p", 'r', "stickIron", 'w', Blocks.wool, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Leggings, "wrw", "w w", "w w", 'w', Blocks.wool, 'r', "stickIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Chest, "wrw", "wtw", "wfw", 'w', Blocks.wool, 'r', "stickIron", 't', AdvancedRocketryBlocks.blockFuelTank, 'f', "fanSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Helmet, "prp", "rgr", "www", 'w', Blocks.wool, 'r', "stickIron", 'p', "plateIron", 'g', Blocks.glass_pane)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJetpack, "cpc", "lsl", "f f", 'c', AdvancedRocketryItems.itemPressureTank, 'f', Items.fire_charge, 's', Items.string, 'l', Blocks.lever, 'p', "plateSteel")); //Tool Recipes GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJackhammer, " pt","imp","di ",'d', Items.diamond, 'm', AdvancedRocketryBlocks.blockMotor, 'p', "plateBronze", 't', "stickTitanium", 'i', "stickIron")); //Other blocks GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSmallAirlockDoor, "pp", "pp","pp", 'p', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCircularLight), "p ", " l ", " ", 'p', "sheetIron", 'l', Blocks.glowstone)); //TEMP RECIPES GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemPlanetIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemMisc,1,1), new ItemStack(Items.coal,1,1), new ItemStack(Items.coal,1,1), new ItemStack(Items.coal,1,1), new ItemStack(Items.coal,1,1) ,new ItemStack(Items.coal,1,1) ,new ItemStack(Items.coal,1,1)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLandingPad), new ItemStack(AdvancedRocketryBlocks.blockConcrete), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemAsteroidChip), trackingCircuit.copy(), AdvancedRocketryItems.itemDataUnit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockDataPipe, 8), "ggg", " d ", "ggg", 'g', Blocks.glass_pane, 'd', AdvancedRocketryItems.itemDataUnit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockEnergyPipe, 32), "ggg", " d ", "ggg", 'g', Items.clay_ball, 'd', "stickCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFluidPipe, 32), "ggg", " d ", "ggg", 'g', Items.clay_ball, 'd', "sheetCopper")); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDrill), LibVulpesBlocks.blockStructureBlock, Items.iron_pickaxe); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockOrientationController), LibVulpesBlocks.blockStructureBlock, Items.compass, userInterface); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockGravityController), LibVulpesBlocks.blockStructureBlock, Blocks.piston, Blocks.redstone_block); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockAltitudeController), LibVulpesBlocks.blockStructureBlock, userInterface, basicCircuit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemLens), " g ", "g g", 'g', Blocks.glass_pane); GameRegistry.addShapelessRecipe(new ItemStack(LibVulpesBlocks.blockRFBattery), new ItemStack(LibVulpesBlocks.blockRFOutput)); GameRegistry.addShapelessRecipe(new ItemStack(LibVulpesBlocks.blockRFOutput), new ItemStack(LibVulpesBlocks.blockRFBattery)); GameRegistry.addShapelessRecipe(largeSolarPanel.copy(), smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMicrowaveReciever), "ggg", "tbc", "aoa", 'g', "plateGold", 't', trackingCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'c', controlCircuitBoard, 'a', advancedCircuit, 'o', opticalSensor)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSolarPanel, "rrr", "gbg", "ppp", 'r' , Items.redstone, 'g', Items.glowstone_dust, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateGold")); GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockSolarGenerator, "itemBattery", LibVulpesBlocks.blockRFOutput, AdvancedRocketryBlocks.blockSolarPanel)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemOreScanner, "lwl", "bgb", " ", 'l', Blocks.lever, 'g', userInterface, 'b', "itemBattery", 'w', advancedCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), " c ","sss", "tot", 'c', "stickCopper", 's', "sheetIron", 'o', AdvancedRocketryItems.itemOreScanner, 't', trackingCircuit)); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockSuitWorkStation), "c","b", 'c', Blocks.crafting_table, 'b', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDockingPort), trackingCircuit, new ItemStack(AdvancedRocketryBlocks.blockLoader, 1,1)); RecipesMachine.getInstance().addRecipe(TileElectrolyser.class, new Object[] {new FluidStack(AdvancedRocketryFluids.fluidOxygen, 100), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 100)}, 100, 20, new FluidStack(FluidRegistry.WATER, 10)); RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new FluidStack(AdvancedRocketryFluids.fluidRocketFuel, 20), 100, 10, new FluidStack(AdvancedRocketryFluids.fluidOxygen, 10), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 10)); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSpaceLaser, "ata", "bec", "gpg", 'a', advancedCircuit, 't', trackingCircuit, 'b', LibVulpesItems.itemBattery, 'e', Items.emerald, 'c', controlCircuitBoard, 'g', "gearTitanium", 'p', LibVulpesBlocks.blockStructureBlock)); } if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockAtmosphereTerraformer), "gdg", "lac", "gbg", 'g', "gearTitaniumAluminide", 'd', "crystalDilithium", 'l', liquidIOBoard, 'a', LibVulpesBlocks.blockAdvStructureBlock, 'c', controlCircuitBoard, 'b', battery2x)); } //Control boards GameRegistry.addRecipe(new ShapedOreRecipe(itemIOBoard, "rvr", "dwd", "dpd", 'r', Items.redstone, 'v', Items.diamond, 'd', "dustGold", 'w', Blocks.wooden_slab, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(controlCircuitBoard, "rvr", "dwd", "dpd", 'r', Items.redstone, 'v', Items.diamond, 'd', "dustCopper", 'w', Blocks.wooden_slab, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(liquidIOBoard, "rvr", "dwd", "dpd", 'r', Items.redstone, 'v', Items.diamond, 'd', new ItemStack(Items.dye, 1, 4), 'w', Blocks.wooden_slab, 'p', "plateIron")); //Cutting Machine RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 0), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 2), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemWafer, 4, 0), 300, 100, "bouleSilicon"); //Lathe RecipesMachine.getInstance().addRecipe(TileLathe.class, MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK")), 300, 100, "ingotIron"); //Precision Assembler recipes RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), 900, 100, Items.gold_ingot, Items.redstone, "waferSilicon"); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1), 900, 100, Items.gold_ingot, Blocks.redstone_block, "waferSilicon"); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), 500, 60, Items.emerald, basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, trackingCircuit, 900, 50, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), Items.ender_eye, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, itemIOBoard, 200, 10, "plateSilicon", "plateGold", basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, controlCircuitBoard, 200, 10, "plateSilicon", "plateCopper", basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, liquidIOBoard, 200, 10, "plateSilicon", new ItemStack(Items.dye, 1, 4), basicCircuit, Items.redstone); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,0), 400, 1, Items.redstone, Blocks.redstone_torch, basicCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,1), 400, 1, Items.fire_charge, Items.diamond, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,2), 400, 1, AdvancedRocketryBlocks.blockMotor, "rodTitanium", advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,3), 400, 1, Items.leather_boots, Items.feather, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,4), 400, 1, LibVulpesItems.itemBattery, AdvancedRocketryItems.itemLens, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemAtmAnalyser), 1000, 1, smallBattery, advancedCircuit, "plateTin", AdvancedRocketryItems.itemLens, userInterface); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemBiomeChanger), 1000, 1, smallBattery, advancedCircuit, "plateTin", trackingCircuit, userInterface); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, biomeChanger, 1000, 1, new NumberedOreDictStack("stickCopper", 2), "stickTitanium", new NumberedOreDictStack("waferSilicon", 2), advancedCircuit); //BlastFurnace RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Silicon").getProduct(AllowedProducts.getProductByName("INGOT")), 12000, 1, Blocks.sand); RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Steel").getProduct(AllowedProducts.getProductByName("INGOT")), 6000, 1, "ingotIron", Items.coal); //TODO add 2Al2O3 as output RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("TitaniumAluminide").getProduct(AllowedProducts.getProductByName("INGOT"), 3), 9000, 20, new NumberedOreDictStack("ingotAluminum", 7), new NumberedOreDictStack("ingotTitanium", 3)); //TODO titanium dioxide //Chemical Reactor RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new Object[] {new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge,1, 0), new ItemStack(Items.coal, 1, 1)}, 40, 20, new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge, 1, AdvancedRocketryItems.itemCarbonScrubberCartridge.getMaxDamage())); RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new ItemStack(Items.dye,5,0xF), 100, 1, Items.bone, new FluidStack(AdvancedRocketryFluids.fluidNitrogen, 10)); //Rolling Machine RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 0), 100, 1, "sheetIron", "sheetIron"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 1), 200, 2, "sheetSteel", "sheetSteel"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 2), 100, 1, "sheetAluminum", "sheetAluminum"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 3), 1000, 8, "sheetTitanium", "sheetTitanium"); NetworkRegistry.INSTANCE.registerGuiHandler(this, new zmaster587.advancedRocketry.inventory.GuiHandler()); planetWorldType = new WorldTypePlanetGen("PlanetCold"); spaceWorldType = new WorldTypeSpace("Space"); AdvancedRocketryBiomes.moonBiome = new BiomeGenMoon(config.get(BIOMECATETORY, "moonBiomeId", 90).getInt(), true); AdvancedRocketryBiomes.alienForest = new BiomeGenAlienForest(config.get(BIOMECATETORY, "alienForestBiomeId", 91).getInt(), true); AdvancedRocketryBiomes.hotDryBiome = new BiomeGenHotDryRock(config.get(BIOMECATETORY, "hotDryBiome", 92).getInt(), true); AdvancedRocketryBiomes.spaceBiome = new BiomeGenSpace(config.get(BIOMECATETORY, "spaceBiomeId", 93).getInt(), true); AdvancedRocketryBiomes.stormLandsBiome = new BiomeGenStormland(config.get(BIOMECATETORY, "stormLandsBiomeId", 94).getInt(), true); AdvancedRocketryBiomes.crystalChasms = new BiomeGenCrystal(config.get(BIOMECATETORY, "crystalChasmsBiomeId", 95).getInt(), true); AdvancedRocketryBiomes.swampDeepBiome = new BiomeGenDeepSwamp(config.get(BIOMECATETORY, "deepSwampBiomeId", 96).getInt(), true); AdvancedRocketryBiomes.marsh = new BiomeGenMarsh(config.get(BIOMECATETORY, "marsh", 97).getInt(), true); AdvancedRocketryBiomes.oceanSpires = new BiomeGenOceanSpires(config.get(BIOMECATETORY, "oceanSpires", 98).getInt(), true); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.alienForest); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.spaceBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.stormLandsBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.crystalChasms); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.swampDeepBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.marsh); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.oceanSpires); String[] biomeBlackList = config.getStringList("BlacklistedBiomes", "Planet", new String[] {"7", "8", "9", "127", String.valueOf(AdvancedRocketryBiomes.alienForest.biomeID)}, "List of Biomes to be blacklisted from spawning as BiomeIds, default is: river, sky, hell, void, alienForest"); String[] biomeHighPressure = config.getStringList("HighPressureBiomes", "Planet", new String[] { String.valueOf(AdvancedRocketryBiomes.swampDeepBiome.biomeID), String.valueOf(AdvancedRocketryBiomes.stormLandsBiome.biomeID) }, "Biomes that only spawn on worlds with pressures over 125, will override blacklist. Defaults: StormLands, DeepSwamp"); String[] biomeSingle = config.getStringList("SingleBiomes", "Planet", new String[] { String.valueOf(AdvancedRocketryBiomes.swampDeepBiome.biomeID), String.valueOf(AdvancedRocketryBiomes.crystalChasms.biomeID), String.valueOf(AdvancedRocketryBiomes.alienForest.biomeID), String.valueOf(BiomeGenBase.desertHills.biomeID), String.valueOf(BiomeGenBase.mushroomIsland.biomeID), String.valueOf(BiomeGenBase.extremeHills.biomeID), String.valueOf(BiomeGenBase.icePlains.biomeID) }, "Some worlds have a chance of spawning single biomes contained in this list. Defaults: deepSwamp, crystalChasms, alienForest, desert hills, mushroom island, extreme hills, ice plains"); config.save(); //Prevent these biomes from spawning normally AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.spaceBiome); //Read BlackList from config and register Blacklisted biomes for(String string : biomeBlackList) { try { int id = Integer.parseInt(string); BiomeGenBase biome = BiomeGenBase.getBiome(id); if(biome == null || (biome.biomeID == 0 && id != 0)) logger.warning(String.format("Error blackListing biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerBlackListBiome(biome); } catch (NumberFormatException e) { logger.warning("Error blackListing \"" + string + "\". It is not a valid number"); } } if(zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes) { AdvancedRocketryBiomes.instance.blackListVanillaBiomes(); } //Read and Register High Pressure biomes from config for(String string : biomeHighPressure) { try { int id = Integer.parseInt(string); BiomeGenBase biome = BiomeGenBase.getBiome(id); if(biome == null || (biome.biomeID == 0 && id != 0)) logger.warning(String.format("Error registering high pressure biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerHighPressureBiome(biome); } catch (NumberFormatException e) { logger.warning("Error registering high pressure biome \"" + string + "\". It is not a valid number"); } } //Read and Register Single biomes from config for(String string : biomeSingle) { try { int id = Integer.parseInt(string); BiomeGenBase biome = BiomeGenBase.getBiome(id); if(biome == null || (biome.biomeID == 0 && id != 0)) logger.warning(String.format("Error registering single biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerSingleBiome(biome); } catch (NumberFormatException e) { logger.warning("Error registering single biome \"" + string + "\". It is not a valid number"); } } //Add mappings for multiblockmachines //Data mapping 'D' List<BlockMeta> list = new LinkedList<BlockMeta>(); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 0)); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 8)); TileMultiBlock.addMapping('D', list); } @EventHandler public void postInit(FMLPostInitializationEvent event) { //Register multiblock items with the projector ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCuttingMachine(), (BlockTile)AdvancedRocketryBlocks.blockCuttingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileLathe(), (BlockTile)AdvancedRocketryBlocks.blockLathe); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCrystallizer(), (BlockTile)AdvancedRocketryBlocks.blockCrystallizer); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePrecisionAssembler(), (BlockTile)AdvancedRocketryBlocks.blockPrecisionAssembler); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileObservatory(), (BlockTile)AdvancedRocketryBlocks.blockObservatory); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePlanetAnalyser(), (BlockTile)AdvancedRocketryBlocks.blockPlanetAnalyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRollingMachine(), (BlockTile)AdvancedRocketryBlocks.blockRollingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectricArcFurnace(), (BlockTile)AdvancedRocketryBlocks.blockArcFurnace); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectrolyser(), (BlockTile)AdvancedRocketryBlocks.blockElectrolyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileChemicalReactor(), (BlockTile)AdvancedRocketryBlocks.blockChemicalReactor); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileWarpCore(), (BlockTile)AdvancedRocketryBlocks.blockWarpCore); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileMicrowaveReciever(), (BlockTile)AdvancedRocketryBlocks.blockMicrowaveReciever); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileBiomeScanner(), (BlockTile)AdvancedRocketryBlocks.blockBiomeScanner); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAtmosphereTerraformer(), (BlockTile)AdvancedRocketryBlocks.blockAtmosphereTerraformer); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileSpaceLaser(), (BlockTile)AdvancedRocketryBlocks.blockSpaceLaser); proxy.registerEventHandlers(); proxy.registerKeyBindings(); ARAchivements.register(); //TODO: debug //ClientCommandHandler.instance.registerCommand(new Debugger()); PlanetEventHandler handle = new PlanetEventHandler(); FMLCommonHandler.instance().bus().register(handle); MinecraftForge.EVENT_BUS.register(handle); MinecraftForge.EVENT_BUS.register(new BucketHandler()); CableTickHandler cable = new CableTickHandler(); FMLCommonHandler.instance().bus().register(cable); MinecraftForge.EVENT_BUS.register(cable); InputSyncHandler inputSync = new InputSyncHandler(); FMLCommonHandler.instance().bus().register(inputSync); MinecraftForge.EVENT_BUS.register(inputSync); MinecraftForge.EVENT_BUS.register(new MapGenLander()); if(Loader.isModLoaded("GalacticraftCore") && zmaster587.advancedRocketry.api.Configuration.overrideGCAir) { GalacticCraftHandler eventHandler = new GalacticCraftHandler(); MinecraftForge.EVENT_BUS.register(eventHandler); if(event.getSide().isClient()) FMLCommonHandler.instance().bus().register(eventHandler); } FMLCommonHandler.instance().bus().register(SpaceObjectManager.getSpaceManager()); PacketHandler.init(); FuelRegistry.instance.registerFuel(FuelType.LIQUID, AdvancedRocketryFluids.fluidRocketFuel, 1); GameRegistry.registerWorldGenerator(new OreGenerator(), 100); ForgeChunkManager.setForcedChunkLoadingCallback(instance, new WorldEvents()); //AutoGenned Recipes for(zmaster587.libVulpes.api.material.Material ore : MaterialRegistry.getAllMaterials()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("ORE")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0); if(AllowedProducts.getProductByName("NUGGET").isOfType(ore.getAllowedProducts())) { ItemStack nugget = ore.getProduct(AllowedProducts.getProductByName("NUGGET")); nugget.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(nugget, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("INGOT")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("NUGGET").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("CRYSTAL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("CRYSTAL")), 300, 20, AllowedProducts.getProductByName("DUST").name().toLowerCase() + str); } if(AllowedProducts.getProductByName("BOULE").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("BOULE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str, AllowedProducts.getProductByName("NUGGET").name().toLowerCase() + str); } if(AllowedProducts.getProductByName("STICK").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) { for(String name : ore.getOreDictNames()) if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase() + name)) RecipesMachine.getInstance().addRecipe(TileLathe.class, ore.getProduct(AllowedProducts.getProductByName("STICK")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + name); //ore.getProduct(AllowedProducts.getProductByName("INGOT"))); } if(AllowedProducts.getProductByName("PLATE").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase() + oreDictNames)) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("PLATE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase() + oreDictNames); if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("PLATE"),3), 0, 0, AllowedProducts.getProductByName("BLOCK").name().toLowerCase() + oreDictNames); } } } if(AllowedProducts.getProductByName("SHEET").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("SHEET")), 300, 200, AllowedProducts.getProductByName("PLATE").name().toLowerCase() + oreDictNames); } } if(AllowedProducts.getProductByName("COIL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("COIL")), "ooo", "o o", "ooo",'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); } if(AllowedProducts.getProductByName("FAN").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("FAN")), "p p", " r ", "p p", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase() + str, 'r', AllowedProducts.getProductByName("STICK").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("GEAR").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("GEAR")), "sps", " r ", "sps", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase() + str, 's', AllowedProducts.getProductByName("STICK").name().toLowerCase() + str, 'r', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts())) { ItemStack ingot = ore.getProduct(AllowedProducts.getProductByName("INGOT")); ingot.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(ingot, AllowedProducts.getProductByName("BLOCK").name().toLowerCase() + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("BLOCK")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase() + str)); } } if(AllowedProducts.getProductByName("DUST").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("DUST")), 0, 0, AllowedProducts.getProductByName("ORE").name().toLowerCase() + str); } } } //Handle vanilla integration if(zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood) { for(int i = 0; i < 4; i++) { RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.planks, 6, i), 80, 10, new ItemStack(Blocks.log,1, i)); } RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.planks, 6, 4), 80, 10, new ItemStack(Blocks.log2,1, 0)); } //Handle items from other mods if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) { for(Entry<AllowedProducts, HashSet<String>> entry : modProducts.entrySet()) { if(entry.getKey() == AllowedProducts.getProductByName("PLATE")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("PLATE").isOfType(material.getAllowedProducts())) ) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, OreDictionary.getOres("plate" + str).get(0), 300, 20, "ingot" + str); } } } else if(entry.getKey() == AllowedProducts.getProductByName("STICK")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("STICK").isOfType(material.getAllowedProducts())) ) { //GT registers rods as sticks if(OreDictionary.doesOreNameExist("rod" + str) && OreDictionary.getOres("rod" + str).size() > 0) RecipesMachine.getInstance().addRecipe(TileLathe.class, OreDictionary.getOres("rod" + str).get(0), 300, 20, "ingot" + str); else if(OreDictionary.doesOreNameExist("stick" + str) && OreDictionary.getOres("stick" + str).size() > 0) { RecipesMachine.getInstance().addRecipe(TileLathe.class, OreDictionary.getOres("stick" + str).get(0), 300, 20, "ingot" + str); } } } } } } //Register buckets BucketHandler.INSTANCE.registerBucket(AdvancedRocketryBlocks.blockFuelFluid, AdvancedRocketryItems.itemBucketRocketFuel); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidRocketFuel, new ItemStack(AdvancedRocketryItems.itemBucketRocketFuel), new ItemStack(Items.bucket)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidNitrogen, new ItemStack(AdvancedRocketryItems.itemBucketNitrogen), new ItemStack(Items.bucket)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidHydrogen, new ItemStack(AdvancedRocketryItems.itemBucketHydrogen), new ItemStack(Items.bucket)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidOxygen, new ItemStack(AdvancedRocketryItems.itemBucketOxygen), new ItemStack(Items.bucket)); //Register mixed material's recipes for(MixedMaterial material : MaterialRegistry.getMixedMaterialList()) { RecipesMachine.getInstance().addRecipe(material.getMachine(), material.getProducts(), 100, 10, material.getInput()); } //Register space dimension net.minecraftforge.common.DimensionManager.registerProviderType(zmaster587.advancedRocketry.api.Configuration.spaceDimId, WorldProviderSpace.class, true); net.minecraftforge.common.DimensionManager.registerDimension(zmaster587.advancedRocketry.api.Configuration.spaceDimId,zmaster587.advancedRocketry.api.Configuration.spaceDimId); //Register Whitelisted Sealable Blocks logger.fine("Start registering sealable blocks"); for(String str : sealableBlockWhileList) { Block block = Block.getBlockFromName(str); if(block == null) logger.warning("'" + str + "' is not a valid Block"); else SealableBlockHandler.INSTANCE.addSealableBlock(block); } logger.fine("End registering sealable blocks"); sealableBlockWhileList = null; } @EventHandler public void serverStarted(FMLServerStartedEvent event) { for (int dimId : DimensionManager.getInstance().getLoadedDimensions()) { DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(dimId); if(!properties.isNativeDimension) { if(properties.getId() != zmaster587.advancedRocketry.api.Configuration.MoonId) DimensionManager.getInstance().deleteDimension(properties.getId()); else if (!Loader.isModLoaded("GalacticraftCore")) properties.isNativeDimension = true; } } } @EventHandler public void serverStarting(FMLServerStartingEvent event) { event.registerServerCommand(new WorldCommand()); if(Loader.isModLoaded("GalacticraftCore") ) zmaster587.advancedRocketry.api.Configuration.MoonId = ConfigManagerCore.idDimensionMoon; //Register hard coded dimensions if(!zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().loadDimensions(zmaster587.advancedRocketry.dimension.DimensionManager.filePath)) { int numRandomGeneratedPlanets = 9; int numRandomGeneratedGasGiants = 1; File file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/planetDefs.xml"); logger.info("Checking for config at " + file.getAbsolutePath()); boolean loadedFromXML = false; if(file.exists()) { logger.info("File found!"); XMLPlanetLoader loader = new XMLPlanetLoader(); try { loader.loadFile(file); List<StellarBody> list = loader.readAllPlanets(); for(StellarBody star : list) { DimensionManager.getInstance().addStar(star); numRandomGeneratedPlanets = loader.getMaxNumPlanets(star); numRandomGeneratedGasGiants = loader.getMaxNumGasGiants(star); generateRandomPlanets(star, numRandomGeneratedPlanets, numRandomGeneratedGasGiants); } loadedFromXML = true; } catch(IOException e) { logger.severe("XML planet config exists but cannot be loaded! Defaulting to random gen."); } } if(zmaster587.advancedRocketry.api.Configuration.MoonId == -1) zmaster587.advancedRocketry.api.Configuration.MoonId = DimensionManager.getInstance().getNextFreeDim(); DimensionProperties dimensionProperties = new DimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId); dimensionProperties.setAtmosphereDensityDirect(0); dimensionProperties.averageTemperature = 20; dimensionProperties.gravitationalMultiplier = .166f; //Actual moon value dimensionProperties.setName("Luna"); dimensionProperties.orbitalDist = 150; dimensionProperties.addBiome(AdvancedRocketryBiomes.moonBiome); dimensionProperties.setParentPlanet(DimensionManager.overworldProperties); dimensionProperties.setStar(DimensionManager.getSol()); dimensionProperties.isNativeDimension = !Loader.isModLoaded("GalacticraftCore"); DimensionManager.getInstance().registerDimNoUpdate(dimensionProperties, !Loader.isModLoaded("GalacticraftCore")); if(!loadedFromXML) generateRandomPlanets(DimensionManager.getSol(), numRandomGeneratedPlanets, numRandomGeneratedGasGiants); } else if(Loader.isModLoaded("GalacticraftCore") ) { DimensionManager.getInstance().getDimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId).isNativeDimension = false; } VersionCompat.upgradeDimensionManagerPostLoad(DimensionManager.prevBuild); } private void generateRandomPlanets(StellarBody star, int numRandomGeneratedPlanets, int numRandomGeneratedGasGiants) { Random random = new Random(System.currentTimeMillis()); for(int i = 0; i < numRandomGeneratedGasGiants; i++) { int baseAtm = 180; int baseDistance = 100; DimensionProperties properties = DimensionManager.getInstance().generateRandomGasGiant(star.getId(), "",baseDistance + 50,baseAtm,125,100,100,75); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(8); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(star.getId(), properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); moonProperties.setParentPlanet(properties); star.removePlanet(moonProperties); } } } for(int i = 0; i < numRandomGeneratedPlanets; i++) { int baseAtm = 75; int baseDistance = 100; if(i % 4 == 0) { baseAtm = 0; } else if(i != 6 && (i+2) % 4 == 0) baseAtm = 120; if(i % 3 == 0) { baseDistance = 170; } else if((i + 1) % 3 == 0) { baseDistance = 30; } DimensionProperties properties = DimensionManager.getInstance().generateRandom(star.getId(), baseDistance,baseAtm,125,100,100,75); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(4); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(star.getId(), properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); moonProperties.setParentPlanet(properties); star.removePlanet(moonProperties); } } } } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions(); zmaster587.advancedRocketry.cable.NetworkRegistry.clearNetworks(); SpaceObjectManager.getSpaceManager().onServerStopped(); } @SubscribeEvent public void registerOre(OreRegisterEvent event) { if(!zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) return; for(AllowedProducts product : AllowedProducts.getAllAllowedProducts() ) { if(event.Name.startsWith(product.name().toLowerCase())) { HashSet<String> list = modProducts.get(product); if(list == null) { list = new HashSet<String>(); modProducts.put(product, list); } list.add(event.Name.substring(product.name().length())); } } //GT uses stick instead of Rod if(event.Name.startsWith("stick")) { HashSet<String> list = modProducts.get(AllowedProducts.getProductByName("STICK")); if(list == null) { list = new HashSet<String>(); modProducts.put(AllowedProducts.getProductByName("STICK"), list); } list.add(event.Name.substring("stick".length())); } } //Patch missing mappings @Mod.EventHandler public void missingMappingEvent(FMLMissingMappingsEvent event) { Iterator<MissingMapping> itr = event.getAll().iterator(); while(itr.hasNext()) { MissingMapping mapping = itr.next(); if(mapping.name.equalsIgnoreCase("advancedrocketry:" + LibVulpesItems.itemBattery.getUnlocalizedName())) mapping.remap(LibVulpesItems.itemBattery); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.satellitePowerSource")) mapping.remap(AdvancedRocketryItems.itemSatellitePowerSource); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.circuitplate")) mapping.remap(AdvancedRocketryItems.itemCircuitPlate); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.wafer")) mapping.remap(AdvancedRocketryItems.itemWafer); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.itemUpgrade")) mapping.remap(AdvancedRocketryItems.itemUpgrade); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.dataUnit")) mapping.remap(AdvancedRocketryItems.itemDataUnit); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.satellitePrimaryFunction")) mapping.remap(AdvancedRocketryItems.itemSatellitePrimaryFunction); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.pressureTank")) mapping.remap(AdvancedRocketryItems.itemPressureTank); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.pressureTank")) mapping.remap(AdvancedRocketryItems.itemPressureTank); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.lens")) mapping.remap(AdvancedRocketryItems.itemLens); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.miscpart")) mapping.remap(AdvancedRocketryItems.itemMisc); if(mapping.name.equalsIgnoreCase("advancedRocketry:item.circuitIC")) mapping.remap(AdvancedRocketryItems.itemIC); } } }
package org.unidle.social; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.encrypt.TextEncryptor; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.ConnectionRepository; import org.springframework.stereotype.Component; import org.unidle.domain.User; import org.unidle.repository.UserConnectionRepository; import org.unidle.repository.UserRepository; @Component public class ConnectionRepositoryFactory { private final ConnectionFactoryLocator connectionFactoryLocator; private final TextEncryptor textEncryptor; private final UserConnectionRepository userConnectionRepository; private final UserRepository userRepository; @Autowired public ConnectionRepositoryFactory(final ConnectionFactoryLocator connectionFactoryLocator, final TextEncryptor textEncryptor, final UserConnectionRepository userConnectionRepository, final UserRepository userRepository) { this.connectionFactoryLocator = connectionFactoryLocator; this.textEncryptor = textEncryptor; this.userConnectionRepository = userConnectionRepository; this.userRepository = userRepository; } public ConnectionRepository getConnectionRepository(final String userId) { final User user = userRepository.findOne(Long.valueOf(userId)); return new ConnectionRepositoryImpl(connectionFactoryLocator, textEncryptor, userConnectionRepository, user); } }
package org.glob3.mobile.generated; // IG3MBuilder.cpp // G3MiOSSDK // IG3MBuilder.hpp // G3MiOSSDK public abstract class IG3MBuilder { private GL _gl; private IDownloader _downloader; private IThreadUtils _threadUtils; private Planet _planet; // REMOVED FINAL WORD BY CONVERSOR RULE private java.util.ArrayList<ICameraConstrainer> _cameraConstraints = new java.util.ArrayList<ICameraConstrainer>(); private CameraRenderer _cameraRenderer; private Color _backgroundColor; private LayerSet _layerSet; private TilesRenderParameters _parameters; private TileRenderer _tileRenderer; private Renderer _busyRenderer; private java.util.ArrayList<Renderer> _renderers = new java.util.ArrayList<Renderer>(); private GInitializationTask _initializationTask; private boolean _autoDeleteInitializationTask; private java.util.ArrayList<PeriodicalTask> _periodicalTasks = new java.util.ArrayList<PeriodicalTask>(); private boolean _logFPS; private boolean _logDownloaderStatistics; private UserData _userData; private java.util.ArrayList<ICameraConstrainer> createCameraConstraints() { java.util.ArrayList<ICameraConstrainer> cameraConstraints = new java.util.ArrayList<ICameraConstrainer>(); SimpleCameraConstrainer scc = new SimpleCameraConstrainer(); cameraConstraints.add(scc); return cameraConstraints; } private CameraRenderer createCameraRenderer() { CameraRenderer cameraRenderer = new CameraRenderer(); final boolean useInertia = true; cameraRenderer.addHandler(new CameraSingleDragHandler(useInertia)); final boolean processRotation = true; final boolean processZoom = true; cameraRenderer.addHandler(new CameraDoubleDragHandler(processRotation, processZoom)); cameraRenderer.addHandler(new CameraRotationHandler()); cameraRenderer.addHandler(new CameraDoubleTapHandler()); return cameraRenderer; } private void pvtSetInitializationTask(GInitializationTask initializationTask, boolean autoDeleteInitializationTask) { if (_initializationTask != initializationTask) { if (_initializationTask != null) _initializationTask.dispose(); _initializationTask = initializationTask; } _autoDeleteInitializationTask = autoDeleteInitializationTask; } protected IStorage _storage; protected final G3MWidget create() { if (_gl == null) { ILogger.instance().logError("Logic Error: _gl not initialized"); return null; } if (_storage == null) { _storage = createStorage(); } if (_downloader == null) { _downloader = createDownloader(); } if (_threadUtils == null) { _threadUtils = createThreadUtils(); } if (_planet == null) { _planet = Planet.createEarth(); } if (_cameraConstraints.size() == 0) { _cameraConstraints = createCameraConstraints(); } if (_cameraRenderer == null) { _cameraRenderer = createCameraRenderer(); } if (_tileRenderer == null) { TileRendererBuilder tileRendererBuilder = new TileRendererBuilder(); if (_layerSet != null) { tileRendererBuilder.setLayerSet(_layerSet); } if (_parameters != null) { tileRendererBuilder.setTileRendererParameters(_parameters); } _tileRenderer = tileRendererBuilder.create(); } else { if (_layerSet != null) { ILogger.instance().logWarning("LayerSet will be ignored because TileRenderer was also set"); } if (_parameters != null) { ILogger.instance().logWarning("TilesRendererParameters will be ignored because TileRenderer was also set"); } } Renderer mainRenderer = null; if (_renderers.size() > 0) { mainRenderer = new CompositeRenderer(); ((CompositeRenderer) mainRenderer).addRenderer(_tileRenderer); for (int i = 0; i < _renderers.size(); i++) { ((CompositeRenderer) mainRenderer).addRenderer(_renderers.get(i)); } } else { mainRenderer = _tileRenderer; } if (_busyRenderer == null) { _busyRenderer = new BusyMeshRenderer(); } Color backgroundColor = Color.fromRGBA(_backgroundColor.getRed(), _backgroundColor.getGreen(), _backgroundColor.getBlue(), _backgroundColor.getAlpha()); G3MWidget g3mWidget = G3MWidget.create(_gl, _storage, _downloader, _threadUtils, _planet, _cameraConstraints, _cameraRenderer, mainRenderer, _busyRenderer, backgroundColor, _logFPS, _logDownloaderStatistics, _initializationTask, _autoDeleteInitializationTask, _periodicalTasks); g3mWidget.setUserData(_userData); return g3mWidget; } protected abstract IThreadUtils createThreadUtils(); protected abstract IStorage createStorage(); protected abstract IDownloader createDownloader(); public IG3MBuilder() { _gl = null; _storage = null; _downloader = null; _threadUtils = null; _planet = null; _cameraRenderer = null; _backgroundColor = Color.newFromRGBA((float)0, (float)0.1, (float)0.2, (float)1); _layerSet = null; _parameters = null; _tileRenderer = null; _busyRenderer = null; _initializationTask = null; _autoDeleteInitializationTask = true; _logFPS = false; _logDownloaderStatistics = false; _userData = null; /* _gl = NULL; _storage = NULL; _downloader = NULL; _threadUtils = NULL; _planet = NULL; _cameraRenderer = NULL; _backgroundColor = Color::newFromRGBA((float)0, (float)0.1, (float)0.2, (float)1); _layerSet = NULL; _parameters = NULL; _tileRenderer = NULL; _busyRenderer = new BusyMeshRenderer(); _initializationTask = NULL; _logFPS = false; _logDownloaderStatistics = false; _autoDeleteInitializationTask = true; _userData = NULL; */ } public void dispose() { if (_backgroundColor != null) _backgroundColor.dispose(); ///#ifdef C_CODE // delete _planet; // delete _parameters; ///#endif // delete _gl; // delete _storage; // delete _downloader; // delete _threadUtils; // delete _cameraRenderer; // delete _layerSet; // delete _tileRenderer; // delete _busyRenderer; // delete _initializationTask; // delete _userData; } public final void setGL(GL gl) { if (_gl != gl) { if (_gl != null) _gl.dispose(); _gl = gl; } } public final void setStorage(IStorage storage) { if (_storage != storage) { if (_storage != null) _storage.dispose(); _storage = storage; } } public final void setDownloader(IDownloader downloader) { if (_downloader != downloader) { if (_downloader != null) _downloader.dispose(); _downloader = downloader; } } public final void setThreadUtils(IThreadUtils threadUtils) { if (_threadUtils != threadUtils) { if (_threadUtils != null) _threadUtils.dispose(); _threadUtils = threadUtils; } } public final void setPlanet(Planet planet) { if (_planet != planet) { _planet = planet; } } public final void addCameraConstraint(ICameraConstrainer cameraConstraint) { _cameraConstraints.add(cameraConstraint); } public final void setCameraRenderer(CameraRenderer cameraRenderer) { if (_cameraRenderer != cameraRenderer) { if (_cameraRenderer != null) _cameraRenderer.dispose(); _cameraRenderer = cameraRenderer; } } public final void setBackgroundColor(Color backgroundColor) { if (_backgroundColor != backgroundColor) { if (_backgroundColor != null) _backgroundColor.dispose(); _backgroundColor = backgroundColor; } } public final void setLayerSet(LayerSet layerSet) { if (_tileRenderer == null) { if (_layerSet != layerSet) { if (_layerSet != null) _layerSet.dispose(); _layerSet = layerSet; } } else { ILogger.instance().logWarning("LayerSet will be ignored because TileRenderer was previously set"); } } public final void setTileRendererParameters(TilesRenderParameters parameters) { if (_tileRenderer == null) { if (_parameters != parameters) { _parameters = parameters; } } else { ILogger.instance().logWarning("TilesRendererParameters will be ignored because TileRenderer was previously set"); } } public final void setTileRenderer(TileRenderer tileRenderer) { if (_tileRenderer != tileRenderer) { if (_tileRenderer != null) _tileRenderer.dispose(); _tileRenderer = tileRenderer; } } public final void setBusyRenderer(Renderer busyRenderer) { if (_busyRenderer != busyRenderer) { if (_busyRenderer != null) _busyRenderer.dispose(); _busyRenderer = busyRenderer; } } public final void addRenderer(Renderer renderer) { _renderers.add(renderer); } public final void addPeriodicalTask(PeriodicalTask periodicalTask) { _periodicalTasks.add(periodicalTask); } public final void setLogFPS(boolean logFPS) { _logFPS = logFPS; } public final void setLogDownloaderStatistics(boolean logDownloaderStatistics) { _logDownloaderStatistics = logDownloaderStatistics; } public final void setUserData(UserData userData) { if (_userData != userData) { if (_userData != null) _userData.dispose(); _userData = userData; } } public final void setInitializationTask(GInitializationTask initializationTask) { pvtSetInitializationTask(initializationTask, true // parameter ignored in Java code ); } }
package sb.tasks.jobs.dailypress.agent; import com.jcabi.http.Response; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.wire.AutoRedirectingWire; import com.jcabi.http.wire.CookieOptimizingWire; import com.jcabi.http.wire.RetryWire; import com.jcabi.log.Logger; import org.bson.Document; import org.jsoup.Jsoup; import sb.tasks.ValidProps; import sb.tasks.agent.Agent; import sb.tasks.jobs.dailypress.MagResult; import sb.tasks.jobs.dailypress.PdfFromResponse; import javax.ws.rs.core.HttpHeaders; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; public final class AnSportExpress implements Agent<MagResult> { private static final String VALUE = "value"; private final Document document; private final ValidProps props; private final String phpSessId; private final String user; private final String sess; private final String userAgent; public AnSportExpress(Document document, ValidProps props, Document phpSessId, Document user, Document sess, Document userAgent) { this( document, props, phpSessId == null ? "" : phpSessId.getString(VALUE), user == null ? "" : user.getString(VALUE), sess == null ? "" : sess.getString(VALUE), userAgent == null ? "" : userAgent.getString(VALUE) ); } public AnSportExpress(Document document, ValidProps props, String phpSessId, String user, String sess, String userAgent) { this.document = document; this.props = props; this.phpSessId = phpSessId; this.user = user; this.sess = sess; this.userAgent = userAgent; } @Override public List<MagResult> perform() throws IOException { String url = Jsoup.connect("http: .get() .getElementsByAttribute("data-newspaper-link") .attr("href"); Logger.info(this, String.format("Checking link: %s", url)); File out = new File( props.tmpDir(), String.format("se%s.pdf", new SimpleDateFormat("yyyyMMdd").format(new Date())) ); if (!url.equals(document.get("vars", Document.class).getString("download_url"))) { Response response = new JdkRequest(url) .through(RetryWire.class) .through(CookieOptimizingWire.class) .through(AutoRedirectingWire.class) .header("Upgrade-Insecure-Requests", "0") .header(HttpHeaders.ACCEPT, "application/pdf") .header(HttpHeaders.USER_AGENT, userAgent) .header(HttpHeaders.COOKIE, String.format("PHPSESSID=%s", phpSessId)) .header(HttpHeaders.COOKIE, String.format("se.sess=%s", sess)) .header(HttpHeaders.COOKIE, String.format("se.user=%s", user)) .fetch(); new PdfFromResponse(response).saveTo(out); } else Logger.info(this, String.format("%s already downloaded. Exiting", url)); return Collections.singletonList( new MagResult(out, url, document.get("params", Document.class).getString("text")) ); } }
package se.su.it.cognos.cognosshibauth; import com.cognos.CAM_AAA.authentication.*; import com.cognos.CAM_AAA.authentication.SystemRecoverableException; import com.cognos.CAM_AAA.authentication.UnrecoverableException; import com.cognos.CAM_AAA.authentication.UserRecoverableException; import org.apache.commons.lang.ArrayUtils; import se.su.it.cognos.cognosshibauth.adapters.CognosShibAuthAccount; import se.su.it.cognos.cognosshibauth.adapters.CognosShibAuthVisa; import se.su.it.cognos.cognosshibauth.config.ConfigHandler; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; public class CognosShibAuth implements INamespaceAuthenticationProvider2 { String namespaceFormat = null; String capabilities[] = null; String objectId = null; private Logger LOG = Logger.getLogger(ConfigHandler.class.getName()); private ConfigHandler configHandler = null; public CognosShibAuth() { configHandler = ConfigHandler.instance(); } public IVisa logon(IBiBusHeader2 iBiBusHeader2) throws UserRecoverableException, SystemRecoverableException, UnrecoverableException { CognosShibAuthVisa cognosShibAuthVisa = new CognosShibAuthVisa(configHandler); String remoteUser = getHeaderValue(iBiBusHeader2, configHandler.getHeaderRemoteUser(), true); String givenName = getHeaderValue(iBiBusHeader2, configHandler.getHeaderGivenName(), true); String surname = getHeaderValue(iBiBusHeader2, configHandler.getHeaderSurname(), true); Locale contentLocale = configHandler.getContentLocale(); CognosShibAuthAccount cognosShibAuthAccount = new CognosShibAuthAccount("u:" + remoteUser, remoteUser, givenName, surname, contentLocale); String mail = getHeaderValue(iBiBusHeader2, configHandler.getHeaderMail(), true); cognosShibAuthAccount.setEmail(mail); String businessPhone = getHeaderValue(iBiBusHeader2, configHandler.getHeaderBusinessPhone(), false); cognosShibAuthAccount.setBusinessPhone(businessPhone); String homePhone = getHeaderValue(iBiBusHeader2, configHandler.getHeaderHomePhone(), false); cognosShibAuthAccount.setHomePhone(homePhone); String mobilePhone = getHeaderValue(iBiBusHeader2, configHandler.getHeaderMobilePhone(), false); cognosShibAuthAccount.setMobilePhone(mobilePhone); String faxPhone = getHeaderValue(iBiBusHeader2, configHandler.getHeaderFaxPhone(), false); cognosShibAuthAccount.setFaxPhone(faxPhone); String pagerPhone = getHeaderValue(iBiBusHeader2, configHandler.getHeaderPagerPhone(), false); cognosShibAuthAccount.setPagerPhone(pagerPhone); String postalAddress = getHeaderValue(iBiBusHeader2, configHandler.getHeaderPostalAddress(), false); cognosShibAuthAccount.setPostalAddress(postalAddress); cognosShibAuthVisa.init(cognosShibAuthAccount); return cognosShibAuthVisa; } private String getHeaderValue(IBiBusHeader2 iBiBusHeader2, String header, boolean required) throws SystemRecoverableException { String[] headerValue = iBiBusHeader2.getEnvVarValue(header); //TODO: Use getTrustedEnvVarValue when releasing stable. if(headerValue == null) { LOG.log(Level.INFO, "Header '" + header + "' not found."); if(required) { // Value not found in trusted environment variables. LOG.log(Level.SEVERE, "Header '" + header + "' required but not found, throwing SystemRecoverableException"); throw new SystemRecoverableException("Missing required header '" + header + "'.", header); } } else { String values = ""; for(String s : headerValue) values += s + ", "; LOG.log(Level.FINEST, "Values in '" + header + "': " + values); if(headerValue.length < 1) headerValue = null; } return headerValue == null ? null : headerValue[0]; } public void logoff(IVisa iVisa, IBiBusHeader iBiBusHeader) { CognosShibAuthVisa cognosShibAuthVisa = (CognosShibAuthVisa) iVisa; try { cognosShibAuthVisa.destroy(); } catch (UnrecoverableException e) { LOG.log(Level.SEVERE, "Failed to destroy visa '" + cognosShibAuthVisa + "' during logout."); e.printStackTrace(); } } public IQueryResult search(IVisa iVisa, IQuery iQuery) throws UnrecoverableException { // We can safely assume that we'll get back the same Visa that we issued. CognosShibAuthVisa visa = (CognosShibAuthVisa) iVisa; QueryResult result = new QueryResult(); try { ISearchExpression expression = iQuery.getSearchExpression(); String objectID = expression.getObjectID(); ISearchStep[] steps = expression.getSteps(); // It doesn't make sense to have multiple steps for this provider // since the objects are not hierarchical. if (steps.length != 1) { throw new UnrecoverableException( "Internal Error", "Invalid search expression. Multiple steps is not supported for this namespace."); } int searchType = steps[0].getAxis(); ISearchFilter filter = steps[0].getPredicate(); switch (searchType) { case ISearchStep.SearchAxis.Self : case ISearchStep.SearchAxis.DescendentOrSelf : { if (objectID == null) { if (filter == null || true) {//this.matchesFilter(filter)) { result.addObject(this); // Add current namespace } if (searchType == ISearchStep.SearchAxis.Self) { return result; } else { //sqlCondition.append(QueryUtil.getSqlCondition(filter)); } } else if (objectID.startsWith("u:") && objectID.equals(visa.getAccount().getObjectID())) { if (filter == null || true) {//this.matchesFilter(filter)) { result.addObject(visa.getAccount()); // Add current user } return result; } else if (objectID.startsWith("u:") || objectID.startsWith("r:")) { //String sqlID = objectID.substring(2); //sqlCondition.append(QueryUtil.getSqlCondition(filter)); //if (sqlCondition.length() > 0) { // sqlCondition.append(" AND "); //sqlCondition.append("uid = " + sqlID); } } break; default : { //sqlCondition.append(QueryUtil.getSqlCondition(filter)); } break; } //QueryUtil.query(MS_JDBCDriver.driver, visa.getConnection(), // sqlCondition.toString(), theQuery.getQueryOption(), // theQuery.getProperties(), theQuery.getSortProperties(), // result, this); } catch (Exception e) { e.printStackTrace(); } result.addObject(visa.getAccount()); return result; } public void init(INamespaceConfiguration iNamespaceConfiguration) throws UnrecoverableException { LOG.log(Level.FINEST, "intit method reached"); objectId = iNamespaceConfiguration.getID(); LOG.log(Level.FINE, "ObjectID set to '" + objectId + "'."); List<String> capabilitiesList = configHandler.getCapabilities(); capabilities = capabilitiesList.toArray(new String[capabilitiesList.size()]); } public void destroy() {} public String getNamespaceFormat() { return namespaceFormat; } public void setNamespaceFormat(String s) throws UnrecoverableException { namespaceFormat = s; } public String[] getCapabilities() { return capabilities; } public String getDescription(Locale locale) { return configHandler.getDescription(locale); } public Locale[] getAvailableDescriptionLocales() { List<Locale> locales = configHandler.getDescriptionLocales(); return locales.toArray(new Locale[locales.size()]); } public IBaseClass[] getAncestors() { // TODO: Implement something smart. return null; } public boolean getHasChildren() { return false; } public String getName(Locale locale) { return configHandler.getName(locale); } public Locale[] getAvailableNameLocales() { List<Locale> locales = configHandler.getDescriptionLocales(); return locales.toArray(new Locale[locales.size()]); } public String getObjectID() { return objectId; } private String filterGmaiRole(String gmai){ // urn:mace:swami.se:gmai:su-ivs:analyst:departmentNumber=647 int startGmai = gmai.indexOf("su-ivs:") + 6; int stopGmai = gmai.lastIndexOf(":"); String role = gmai.substring(startGmai, stopGmai); return role; } private String filterGmaiDepartment(String gmai){ // urn:mace:swami.se:gmai:su-ivs:analyst:departmentNumber=647 int startGmai = gmai.indexOf("departmentNumber=") + 17; String group = gmai.substring(startGmai); return group; } }
package top.guhanjie.wine.controller; import java.io.File; import java.util.Map; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import top.guhanjie.wine.util.IdGenerator; @Controller public class UploadController extends BaseController{ private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class); @ResponseBody @RequestMapping(value="/upload") public Map<String, Object> upload(@RequestParam("imgType") String type, @RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception{ if(!file.isEmpty()) { int suffixIdx = name.lastIndexOf('.'); String suffix = (suffixIdx != -1) ? name.substring(suffixIdx) : ".jpg"; String destFileName = type+"-"+IdGenerator.getShortUuid()+suffix; //File destFile = new File(servletContext.getRealPath("/")+"/WEB-INF/assets/images/"+destFileName); File destFile = new File("/data/wwwroot/www.guhanjie.top/wine/resources/images/"+destFileName); LOGGER.info("uploading image file[{}]", destFile.getAbsolutePath()); if(!destFile.exists()) { destFile.createNewFile(); } file.transferTo(destFile); return success("images/"+destFileName); } else { LOGGER.warn("upload image file, but file is empty."); return fail(""); } } }
package uk.ac.ebi.phenotype.solr.indexer; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import uk.ac.ebi.phenotype.data.imits.EncodedOrganisationConversionMap; import uk.ac.ebi.phenotype.pojo.SexType; import uk.ac.ebi.phenotype.service.dto.GenotypePhenotypeDTO; import uk.ac.ebi.phenotype.solr.indexer.exceptions.IndexerException; import uk.ac.ebi.phenotype.solr.indexer.exceptions.ValidationException; import javax.annotation.Resource; import javax.sql.DataSource; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.FileInputStream; import java.io.IOException; import java.sql.*; import java.util.*; public class PreqcIndexer extends AbstractIndexer { private static final Logger logger = LoggerFactory.getLogger(PreqcIndexer.class); @Autowired @Qualifier("preqcIndexing") SolrServer preqcCore; @Resource(name = "globalConfiguration") Map<String, String> config; @Autowired @Qualifier("ontodbDataSource") DataSource ontodbDataSource; @Autowired @Qualifier("komp2DataSource") DataSource komp2DataSource; @Autowired EncodedOrganisationConversionMap dccMapping; private static Map<String, String> geneSymbol2IdMapping = new HashMap<>(); private static Map<String, AlleleDTO> alleleSymbol2NameIdMapping = new HashMap<>(); private static Map<String, String> strainId2NameMapping = new HashMap<>(); private static Map<String, String> pipelineSid2NameMapping = new HashMap<>(); private static Map<String, String> procedureSid2NameMapping = new HashMap<>(); private static Map<String, String> parameterSid2NameMapping = new HashMap<>(); private static Map<String, String> projectMap = new HashMap<>(); private static Map<String, String> resourceMap = new HashMap<>(); private static Map<String, String> mpId2TermMapping = new HashMap<>(); private static Map<Integer, String> mpNodeId2MpIdMapping = new HashMap<>(); private static Map<String, String> mpId2NodeIdsMapping = new HashMap<>(); private static Map<Integer, Node2TopDTO> mpNodeId2TopLevelMapping = new HashMap<>(); private static Map<Integer, String> mpNodeId2IntermediateNodeIdsMapping = new HashMap<>(); private static Map<String, List<MpTermDTO>> intermediateMpTerms = new HashMap<>(); private static Map<String, List<MpTermDTO>> topMpTerms = new HashMap<>(); private static Map<String, String> zygosityMapping = new HashMap<>(); private static Set<String> postQcData = new HashSet<>(); private Connection conn_komp2 = null; private Connection conn_ontodb = null; private String preqcXmlFilename; @Override public void validateBuild() throws IndexerException { Long numFound = getDocumentCount(preqcCore); if (numFound <= MINIMUM_DOCUMENT_COUNT) throw new IndexerException(new ValidationException("Actual preqc document count is " + numFound + ".")); if (numFound != documentCount) logger.warn("WARNING: Added " + documentCount + " preqc documents but SOLR reports " + numFound + " documents."); else logger.info("validateBuild(): Indexed " + documentCount + " preqc documents."); } @Override public void run() throws IndexerException { long start = System.currentTimeMillis(); logger.info(" start time: " + (System.currentTimeMillis() - start)); zygosityMapping.put("Heterozygous", "heterozygote"); zygosityMapping.put("Homozygous", "homozygote"); zygosityMapping.put("Hemizygous", "hemizygote"); Set<String> bad = new HashSet<>(); try { conn_komp2 = komp2DataSource.getConnection(); conn_ontodb = ontodbDataSource.getConnection(); preqcXmlFilename = config.get("preqcXmlFilename"); doGeneSymbol2IdMapping(); doAlleleSymbol2NameIdMapping(); doStrainId2NameMapping(); doImpressSid2NameMapping(); doOntologyMapping(); populatePostQcData(); populateResourceMap(); preqcCore.deleteByQuery("*:*"); Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(preqcXmlFilename)); Element rootElement = document.getDocumentElement(); NodeList nodes = rootElement.getElementsByTagName("uk.ac.ebi.phenotype.pojo.PhenotypeCallSummary"); logger.info("length: " + nodes.getLength()); logger.info(" read document time: " + (System.currentTimeMillis() - start)); int counter = 1; for (int i = 0; i < nodes.getLength(); ++ i) { Element e = (Element) nodes.item(i); NodeList childNodes = e.getChildNodes(); Integer id = null; String colonyId = null; Double pValue = null; String sex = null; String phenotypeTerm = null; String externalId = null; String zygosity = null; String datasource = null; String project = null; String gene = null; Double effectSize = null; String strain = null; String allele = null; String pipeline = null; String procedure = null; String parameter = null; String phenotypingCenter = null; for (int j = 0; j < childNodes.getLength(); ++ j) { Node cnode = childNodes.item(j); if (cnode.getNodeType() == Node.ELEMENT_NODE) { switch (cnode.getNodeName()) { case "id": id = Integer.parseInt(cnode.getTextContent()); break; case "colonyId": colonyId = cnode.getTextContent(); break; case "pValue": pValue = Double.parseDouble(cnode.getTextContent()); break; case "sex": sex = cnode.getTextContent(); break; case "phenotypeTerm": phenotypeTerm = cnode.getTextContent(); break; case "externalId": externalId = cnode.getTextContent(); break; case "zygosity": zygosity = cnode.getTextContent(); break; case "datasource": datasource = cnode.getTextContent(); break; case "project": project = cnode.getTextContent(); break; case "gene": gene = cnode.getTextContent(); break; case "effectSize": effectSize = Double.parseDouble(cnode.getTextContent()); break; case "strain": strain = cnode.getTextContent(); break; case "allele": allele = cnode.getTextContent().replace("<sup>", "<").replace("</sup>", ">"); break; case "pipeline": pipeline = cnode.getTextContent(); break; case "procedure": procedure = cnode.getTextContent(); break; case "parameter": parameter = cnode.getTextContent(); break; case "phenotypingCenter": phenotypingCenter = cnode.getTextContent().toUpperCase(); break; } } } // Skip this one: phenotypeTerm is null if (phenotypeTerm == null) { logger.warn("Phenotype term is missing for record with id {}", id); continue; } // Skip this one: pValue not significant OR phenotypeTerm is MA if ((pValue != null && pValue >= 0.0001) || phenotypeTerm.startsWith("MA:")) {//|| id != 726238) { continue; } if (mpId2TermMapping.get(phenotypeTerm) == null) { bad.add(phenotypeTerm); continue; } // Skip if we already have this data postQC phenotypingCenter = dccMapping.dccCenterMap.containsKey(phenotypingCenter) ? dccMapping.dccCenterMap.get(phenotypingCenter) : phenotypingCenter; if (postQcData.contains(StringUtils.join(Arrays.asList(new String[]{colonyId, parameter, phenotypingCenter.toUpperCase()}), "_"))) { continue; } GenotypePhenotypeDTO o = new GenotypePhenotypeDTO(); // Procedure prefix is the first two strings of the parameter after splitting on underscore // i.e. IMPC_BWT_001_001 => IMPC_BWT String procedurePrefix = StringUtils.join(Arrays.asList(parameter.split("_")).subList(0, 2), "_"); if (GenotypePhenotypeIndexer.source3iProcedurePrefixes.contains(procedurePrefix)) { // o.setResourceName("3i"); // o.setResourceFullname("Infection, Immunity and Immunophenotyping consortium"); o.setResourceName(StatisticalResultIndexer.RESOURCE_3I.toUpperCase()); o.setResourceFullname(resourceMap.get(StatisticalResultIndexer.RESOURCE_3I.toUpperCase())); } else { o.setResourceName(datasource); if(resourceMap.containsKey(project.toUpperCase())) { o.setResourceFullname(resourceMap.get(project.toUpperCase())); } } o.setProjectName(project); if(projectMap.containsKey(project.toUpperCase())) { o.setProjectFullname(projectMap.get(project.toUpperCase())); } o.setColonyId(colonyId); o.setExternalId(externalId); o.setStrainAccessionId(strain); o.setStrainName(strainId2NameMapping.get(strain)); o.setMarkerSymbol(gene); o.setMarkerAccessionId(geneSymbol2IdMapping.get(gene)); o.setPipelineName(pipelineSid2NameMapping.get(pipeline)); o.setPipelineStableId(pipeline); o.setProcedureName(procedureSid2NameMapping.get(procedure)); o.setProcedureStableId(procedure); o.setParameterName(parameterSid2NameMapping.get(parameter)); o.setParameterStableId(parameter); o.setMpTermId(phenotypeTerm); o.setMpTermName(mpId2TermMapping.get(phenotypeTerm)); o.setP_value(pValue); o.setEffect_size(effectSize); if ( ! zygosityMapping.containsKey(zygosity)) { logger.warn("Zygosity {} not found for record id {}", zygosity, id); continue; } o.setZygosity(zygosityMapping.get(zygosity)); if (alleleSymbol2NameIdMapping.get(allele) == null) { // use fake id if we cannot find the symbol from komp2 o.setAlleleAccessionId(createFakeIdFromSymbol(allele)); o.setAlleleName(allele); } else { o.setAlleleAccessionId(alleleSymbol2NameIdMapping.get(allele).acc); o.setAlleleName(alleleSymbol2NameIdMapping.get(allele).name); } o.setAlleleSymbol(allele); if (dccMapping.dccCenterMap.containsKey(phenotypingCenter)) { o.setPhenotypingCenter(dccMapping.dccCenterMap.get(phenotypingCenter)); } else { o.setPhenotypingCenter(phenotypingCenter); } // Set the intermediate terms List<String> ids = new ArrayList<>(); List<String> names = new ArrayList<>(); for (MpTermDTO mp : getIntermediateMpTerms(phenotypeTerm)) { ids.add(mp.id); names.add(mp.name); } o.setIntermediateMpTermId(ids); o.setIntermediateMpTermName(names); // Set the top level terms ids = new ArrayList<>(); names = new ArrayList<>(); for (MpTermDTO mp : getTopMpTerms(phenotypeTerm)) { ids.add(mp.id); names.add(mp.name); } o.setTopLevelMpTermId(ids); o.setTopLevelMpTermName(names); if (sex.equals("Both")) { // use incremental id instead of id field from Harwell o.setId(counter ++); o.setSex(SexType.female.getName()); documentCount++; preqcCore.addBean(o); o.setId(counter ++); o.setSex(SexType.male.getName()); documentCount++; preqcCore.addBean(o); } else { o.setId(counter ++); try { SexType.valueOf(sex.toLowerCase()); } catch (IllegalArgumentException se) { logger.error("Got unexpected sex value '{}' from PreQC file. Not loading", se); continue; } o.setSex(sex.toLowerCase()); documentCount++; preqcCore.addBean(o); } if (counter % 1000 == 0) { logger.info("Added {} preqc documents to index", counter); } } preqcCore.commit(); } catch (ParserConfigurationException | SAXException | SQLException | SolrServerException | IOException e) { throw new IndexerException(e); } logger.info("time: " + (System.currentTimeMillis() - start)); if (bad.size() > 0) { logger.warn("found {} unique mps not in ontodb", bad.size()); logger.warn("MP terms not found: {} ", StringUtils.join(bad, ",")); } } public String createFakeIdFromSymbol(String alleleSymbol) { String fakeId = null; ResultSet rs = null; Statement statement = null; String query = "select CONCAT('NULL-', UPPER(SUBSTR(MD5('" + alleleSymbol + "'),1,10))) as fakeId"; try { statement = conn_komp2.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { // Retrieve by column name fakeId = rs.getString("fakeId"); } } catch (SQLException e) { e.printStackTrace(); } return fakeId; } public void doGeneSymbol2IdMapping() { ResultSet rs = null; Statement statement = null; String query = "select acc, symbol from genomic_feature"; try { statement = conn_komp2.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { // Retrieve by column name String acc = rs.getString("acc"); String symbol = rs.getString("symbol"); // logger.error(acc + " -- "+ symbol); geneSymbol2IdMapping.put(symbol, acc); } } catch (SQLException e) { e.printStackTrace(); } } public void populateResourceMap() throws SQLException { String projQuery = "SELECT p.name as name, p.fullname as fullname FROM project p"; String resQuery = "SELECT db.short_name as name, db.name as fullname FROM external_db db "; try (PreparedStatement p = conn_komp2.prepareStatement(projQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { p.setFetchSize(Integer.MIN_VALUE); ResultSet r = p.executeQuery(); while (r.next()) { projectMap.put(r.getString("name").toUpperCase(), r.getString("fullname")); } } try (PreparedStatement p = conn_komp2.prepareStatement(resQuery, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { p.setFetchSize(Integer.MIN_VALUE); ResultSet r = p.executeQuery(); while (r.next()) { resourceMap.put(r.getString("name").toUpperCase(), r.getString("fullname")); } } } public void doImpressSid2NameMapping() { Map<String, Map> impressMapping = new HashMap<>(); impressMapping.put("phenotype_pipeline", pipelineSid2NameMapping); impressMapping.put("phenotype_procedure", procedureSid2NameMapping); impressMapping.put("phenotype_parameter", parameterSid2NameMapping); ResultSet rs = null; Statement statement = null; for (Map.Entry entry : impressMapping.entrySet()) { String tableName = entry.getKey().toString(); Map<String, String> mapping = (Map) entry.getValue(); String query = "select name, stable_id from " + tableName; try { statement = conn_komp2.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { // Retrieve by column name String sid = rs.getString("stable_id"); String name = rs.getString("name"); if (tableName.equals("phenotype_procedure")) { // Harwell does not include version in // procedure_stable_id sid = sid.replaceAll("_\\d+$", ""); } mapping.put(sid, name); } } catch (SQLException e) { e.printStackTrace(); } } } public void doAlleleSymbol2NameIdMapping() { ResultSet rs = null; Statement statement = null; String query = "select acc, symbol, name from allele"; try { statement = conn_komp2.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { // Retrieve by column name String acc = rs.getString("acc"); String symbol = rs.getString("symbol"); String name = rs.getString("name"); // logger.error(acc + " -- "+ symbol); AlleleDTO al = new AlleleDTO(); al.acc = acc; al.name = name; alleleSymbol2NameIdMapping.put(symbol, al); } } catch (SQLException e) { e.printStackTrace(); } } public void doStrainId2NameMapping() { ResultSet rs = null; Statement statement = null; String query = "select acc, name from strain"; try { statement = conn_komp2.createStatement(); rs = statement.executeQuery(query); while (rs.next()) { // Retrieve by column name String acc = rs.getString("acc"); String name = rs.getString("name"); //logger.error(acc + " -- "+ name); strainId2NameMapping.put(acc, name); } } catch (SQLException e) { e.printStackTrace(); } } public void doOntologyMapping() { ResultSet rs1, rs2, rs3, rs4, rs45 = null; Statement statement = null; // all MPs String query1 = "select ti.term_id, ti.name, nt.node_id from mp_term_infos ti, mp_node2term nt where ti.term_id=nt.term_id and ti.term_id !='MP:0000001'"; // all top_level nodes of MP String query2 = "select lv.node_id as mp_node_id, ti.term_id, ti.name from mp_node_top_level lv" + " inner join mp_node2term nt on lv.top_level_node_id=nt.node_id" + " inner join mp_term_infos ti on nt.term_id=ti.term_id" + " and ti.term_id!='MP:0000001'"; // all nodes of MPs String query3 = "select ti.term_id, group_concat(nt.node_id) as nodeIds from mp_term_infos ti, mp_node2term nt where ti.term_id=nt.term_id and ti.term_id !='MP:0000001' group by ti.term_id order by ti.term_id"; // all intermediate nodes of MP nodes String query4 = "select child_node_id, group_concat(node_id) as intermediate_nodeIds from mp_node_subsumption_fullpath group by child_node_id"; try { // we need to create a new state for each query // otherwise we get "Operation not allowed after ResultSet closed" // error statement = conn_ontodb.createStatement(); rs1 = statement.executeQuery(query1); statement = conn_ontodb.createStatement(); rs2 = statement.executeQuery(query2); statement = conn_ontodb.createStatement(); rs3 = statement.executeQuery(query3); statement = conn_ontodb.createStatement(); rs4 = statement.executeQuery(query4); while (rs1.next()) { String mp_term_id = rs1.getString("term_id"); String mp_term_name = rs1.getString("name"); int mp_node_id = rs1.getInt("node_id"); // logger.error("rs1: " + mp_term_id + " -- "+ mp_term_name); // logger.error("rs1: " + mp_node_id + " -- "+ mp_term_name); mpId2TermMapping.put(mp_term_id, mp_term_name); mpNodeId2MpIdMapping.put(mp_node_id, mp_term_id); } // top level MPs while (rs2.next()) { int top_level_mp_node_id = rs2.getInt("mp_node_id"); String top_level_mp_term_id = rs2.getString("term_id"); String top_level_mp_term_name = rs2.getString("name"); // logger.error("rs2: " + top_level_mp_node_id + " --> " + Node2TopDTO n2t = new Node2TopDTO(); n2t.topLevelMpTermId = top_level_mp_term_id; n2t.topLevelMpTermName = top_level_mp_term_name; mpNodeId2TopLevelMapping.put(top_level_mp_node_id, n2t); } while (rs3.next()) { String mp_node_ids = rs3.getString("nodeIds"); String mp_term_id = rs3.getString("term_id"); // logger.error("rs3: " + mp_term_id + " -- > " + mp_node_ids); mpId2NodeIdsMapping.put(mp_term_id, mp_node_ids); } // intermediate nodeId mapping while (rs4.next()) { int child_node_id = rs4.getInt("child_node_id"); String intermediate_nodeIds = rs4.getString("intermediate_nodeIds"); // logger.error("rs4: " + child_node_id + " -- > " + // intermediate_nodeIds); mpNodeId2IntermediateNodeIdsMapping.put(child_node_id, intermediate_nodeIds); } } catch (SQLException e) { e.printStackTrace(); } } public List<MpTermDTO> getIntermediateMpTerms(String mpId) { if ( ! intermediateMpTerms.containsKey(mpId)) { // default to empty list intermediateMpTerms.put(mpId, new ArrayList<MpTermDTO>()); // MP:0012441 -- > 618,732,741,971,1090,1204,1213 if (mpId2NodeIdsMapping.containsKey(mpId)) { String[] nodeIdsStr = mpId2NodeIdsMapping.get(mpId).split(","); List<MpTermDTO> mps = new ArrayList<>(); for (int i = 0; i < nodeIdsStr.length; i ++) { int childNodeId = Integer.parseInt(nodeIdsStr[i]); List<MpTermDTO> top = getTopMpTerms(mpId); // top level mp do not have intermediate mp if (mpNodeId2IntermediateNodeIdsMapping.get(childNodeId) != null) { String[] intermediateNodeIdsStr = mpNodeId2IntermediateNodeIdsMapping.get(childNodeId).split(","); for (int j = 0; j < intermediateNodeIdsStr.length; j ++) { int intermediateNodeId = Integer.parseInt(intermediateNodeIdsStr[j]); MpTermDTO mp = new MpTermDTO(); mp.id = mpNodeId2MpIdMapping.get(intermediateNodeId); mp.name = mpId2TermMapping.get(mp.id); // don't want to include self as intermediate parent if (childNodeId != intermediateNodeId && ! top.contains(mp)) { mps.add(mp); } } } } // added only we got intermediates if (mps.size() != 0) { intermediateMpTerms.put(mpId, mps); } } } return intermediateMpTerms.get(mpId); } public List<MpTermDTO> getTopMpTerms(String mpId) { if ( ! topMpTerms.containsKey(mpId)) { // default to empty list topMpTerms.put(mpId, new ArrayList<MpTermDTO>()); // MP:0012441 -- > 618,732,741,971,1090,1204,1213 if (mpId2NodeIdsMapping.containsKey(mpId)) { String[] nodeIdsStr = mpId2NodeIdsMapping.get(mpId).split(","); List<MpTermDTO> mps = new ArrayList<>(); for (int i = 0; i < nodeIdsStr.length; i ++) { int topLevelMpNodeId = Integer.parseInt(nodeIdsStr[i]); // System.out.println(mpId + " - top_level_node_id: " + // topLevelMpNodeId); if (mpNodeId2TopLevelMapping.containsKey(topLevelMpNodeId)) { MpTermDTO mp = new MpTermDTO(); mp.id = mpNodeId2TopLevelMapping.get(topLevelMpNodeId).topLevelMpTermId; mp.name = mpNodeId2TopLevelMapping.get(topLevelMpNodeId).topLevelMpTermName; mps.add(mp); } } topMpTerms.put(mpId, mps); } } return topMpTerms.get(mpId); } public void populatePostQcData() { String query = "SELECT DISTINCT CONCAT(e.colony_id, '_', o.parameter_stable_id, '_', UPPER(org.name)) AS data_value " + "FROM observation o " + "INNER JOIN experiment_observation eo ON eo.observation_id=o.id " + "INNER JOIN experiment e ON e.id=eo.experiment_id " + "INNER JOIN organisation org ON org.id=e.organisation_id " + "WHERE e.colony_id IS NOT NULL " + "UNION " + "SELECT DISTINCT CONCAT(ls.colony_id, '_', o.parameter_stable_id, '_', UPPER(org.name)) AS data_value " + "FROM observation o " + "INNER JOIN live_sample ls ON ls.id=o.biological_sample_id " + "INNER JOIN biological_sample bs ON bs.id=o.biological_sample_id " + "INNER JOIN organisation org ON org.id=bs.organisation_id " + "WHERE bs.sample_group='experimental' " ; try (PreparedStatement p = conn_komp2.prepareStatement(query)) { ResultSet resultSet = p.executeQuery(); while (resultSet.next()) { postQcData.add(resultSet.getString("data_value")); } } catch (SQLException e) { e.printStackTrace(); } } private class Node2TopDTO { String topLevelMpTermId; String topLevelMpTermName; } private class AlleleDTO { String symbol; String acc; String name; } public class MpTermDTO { String id; String name; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MpTermDTO other = (MpTermDTO) obj; if ( ! getOuterType().equals(other.getOuterType())) { return false; } if (id == null) { if (other.id != null) { return false; } } else if ( ! id.equals(other.id)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if ( ! name.equals(other.name)) { return false; } return true; } private PreqcIndexer getOuterType() { return PreqcIndexer.this; } } @Override public void initialise(String[] args) throws IndexerException { super.initialise(args); } public static void main(String[] args) throws IndexerException { PreqcIndexer main = new PreqcIndexer(); main.initialise(args); main.run(); main.validateBuild(); logger.info("Process finished. Exiting."); } @Override protected Logger getLogger() { return logger; } }
package vcs.citydb.wfs.listener; import org.citydb.config.Config; import org.citydb.config.project.database.DatabaseConfig; import org.citydb.config.project.exporter.ExportConfig; import org.citydb.config.project.global.GlobalConfig; import org.citydb.config.project.global.LogFileMode; import org.citydb.core.ade.ADEExtensionManager; import org.citydb.core.database.connection.DatabaseConnectionPool; import org.citydb.core.database.schema.mapping.SchemaMapping; import org.citydb.core.database.schema.mapping.SchemaMappingException; import org.citydb.core.database.schema.mapping.SchemaMappingValidationException; import org.citydb.core.database.schema.util.SchemaMappingUtil; import org.citydb.core.registry.ObjectRegistry; import org.citydb.core.util.CoreConstants; import org.citydb.core.util.Util; import org.citydb.util.log.Logger; import org.citygml4j.CityGMLContext; import org.citygml4j.builder.jaxb.CityGMLBuilder; import org.citygml4j.builder.jaxb.CityGMLBuilderException; import org.citygml4j.model.citygml.ade.ADEException; import org.citygml4j.model.citygml.ade.binding.ADEContext; import org.citygml4j.xml.schema.SchemaHandler; import org.geotools.referencing.CRS; import org.geotools.referencing.factory.DeferredAuthorityFactory; import org.geotools.util.WeakCollectionCleaner; import org.xml.sax.SAXException; import vcs.citydb.wfs.config.Constants; import vcs.citydb.wfs.config.WFSConfig; import vcs.citydb.wfs.config.WFSConfigLoader; import vcs.citydb.wfs.config.logging.ConsoleLog; import vcs.citydb.wfs.config.logging.FileLog; import vcs.citydb.wfs.exception.AccessControlException; import vcs.citydb.wfs.exception.WFSException; import vcs.citydb.wfs.security.AccessController; import vcs.citydb.wfs.util.DatabaseConnector; import vcs.citydb.wfs.util.RequestLimiter; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.annotation.WebListener; import javax.xml.bind.JAXBException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Driver; import java.sql.DriverManager; import java.time.DateTimeException; import java.time.ZoneId; import java.util.Enumeration; import java.util.TimeZone; import java.util.stream.Stream; @WebListener public class WebServiceInitializer implements ServletContextListener { private final Logger log = Logger.getInstance(); private final Util.URLClassLoader classLoader = new Util.URLClassLoader(getClass().getClassLoader()); @Override public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); ADEExtensionManager adeManager = ADEExtensionManager.getInstance(); ObjectRegistry registry = ObjectRegistry.getInstance(); Config config = registry.getConfig(); SchemaMapping schemaMapping; CityGMLBuilder cityGMLBuilder; WFSConfig wfsConfig; // read 3DCityDB schema mapping and register with object registry try { schemaMapping = SchemaMappingUtil.getInstance().unmarshal(CoreConstants.CITYDB_SCHEMA_MAPPING_FILE); registry.setSchemaMapping(schemaMapping); } catch (JAXBException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to read 3DCityDB schema mapping file.", e)); return; } catch (SchemaMappingException | SchemaMappingValidationException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("The 3DCityDB schema mapping file is invalid.", e)); return; } // load ADE extensions String adeExtensionsPath = Paths.get(Constants.ADE_EXTENSIONS_PATH).isAbsolute() ? Constants.ADE_EXTENSIONS_PATH : context.getRealPath(Constants.ADE_EXTENSIONS_PATH); if (Files.exists(Paths.get(adeExtensionsPath))) { try (Stream<Path> stream = Files.walk(Paths.get(adeExtensionsPath)) .filter(path -> path.getFileName().toString().toLowerCase().endsWith(".jar"))) { stream.forEach(classLoader::addPath); adeManager.loadExtensions(classLoader); adeManager.loadSchemaMappings(schemaMapping); } catch (IOException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to initialize ADE extension support.", e)); return; } } // initialize JAXB context for CityGML, ADE and WFS schemas and register with object registry try { CityGMLContext cityGMLContext = CityGMLContext.getInstance(); for (ADEContext adeContext : adeManager.getADEContexts()) { cityGMLContext.registerADEContext(adeContext); } cityGMLBuilder = cityGMLContext.createCityGMLBuilder(classLoader, "net.opengis.wfs._2", "net.opengis.ows._1", "net.opengis.fes._2"); registry.setCityGMLBuilder(cityGMLBuilder); } catch (CityGMLBuilderException | ADEException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to initialize citygml4j context.", e)); return; } // initialize and register CityGML XML schema handler try { SchemaHandler schemaHandler = SchemaHandler.newInstance(); registry.register(schemaHandler); } catch (SAXException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to initialize CityGML XML schema parser.", e)); return; } // load WFS configuration file and register with object registry try { wfsConfig = WFSConfigLoader.load(context); registry.register(wfsConfig); } catch (JAXBException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to load WFS config from " + Constants.CONFIG_FILE + '.')); return; } // create request limiter and register with object registry registry.register(new RequestLimiter(wfsConfig)); // create access controller and register with object registry try { AccessController accessController = AccessController.build(wfsConfig); registry.register(accessController); } catch (AccessControlException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to initialize access control rules.", e)); return; } // create 3DCityDB dummy configuration and register with object registry initConfig(config, wfsConfig); // initialize logging try { initLogging(wfsConfig, context); log.info("Starting " + getClass().getPackage().getImplementationTitle() + ", version " + getClass().getPackage().getImplementationVersion() + "."); } catch (ServletException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, e); registry.getEventDispatcher().shutdownNow(); return; } // switch time zone if (wfsConfig.getServer().isSetTimeZone()) { log.debug("Setting time zone to " + wfsConfig.getServer().getTimeZone() + "."); try { TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of(wfsConfig.getServer().getTimeZone())); TimeZone.setDefault(timeZone); log.info("Time zone set to " + wfsConfig.getServer().getTimeZone() + " [" + timeZone.getDisplayName() + "]."); } catch (DateTimeException e) { context.setAttribute(Constants.INIT_ERROR_ATTRNAME, new ServletException("Failed to set time zone to " + wfsConfig.getServer().getTimeZone() + ".", e)); return; } } // initialize database connection pool try { DatabaseConnector.connect(config); } catch (WFSException e) { e.getExceptionMessages().forEach(msg -> msg.getExceptionTexts().forEach(log::error)); } // log ADE exceptions if (adeManager.hasExceptions()) { adeManager.logExceptions(); } // preprocess advertised CityGML and ADE feature types wfsConfig.getFeatureTypes().preprocessFeatureTypes(); // GeoTools - don't allow the connection to the EPSG database to time out System.setProperty("org.geotools.epsg.factory.timeout", "-1"); CRS.cleanupThreadLocals(); // log registered JDBC drivers ClassLoader loader = Thread.currentThread().getContextClassLoader(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == loader) { log.debug("Registered JDBC driver " + driver); } } } @Override public void contextDestroyed(ServletContextEvent event) { ServletContext context = event.getServletContext(); ObjectRegistry registry = ObjectRegistry.getInstance(); // remove initialization error context.removeAttribute(Constants.INIT_ERROR_ATTRNAME); // disconnect connection pool DatabaseConnectionPool connectionPool = DatabaseConnectionPool.getInstance(); if (connectionPool.isConnected()) { connectionPool.purge(); connectionPool.disconnect(); } // shutdown event dispatcher thread if (registry.getEventDispatcher() != null) { try { registry.getEventDispatcher().shutdownAndWait(); } catch (InterruptedException e) { registry.getEventDispatcher().shutdownNow(); } } // deregister JDBC drivers loaded by this web application ClassLoader loader = Thread.currentThread().getContextClassLoader(); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == loader) { try { DriverManager.deregisterDriver(driver); log.debug("Unregistered JDBC driver " + driver); } catch (Exception e) { log.error("Failed to unload JDBC driver " + driver, e); } } } // some GeoTools related stuff WeakCollectionCleaner.DEFAULT.exit(); CRS.cleanupThreadLocals(); DeferredAuthorityFactory.exit(); // free classloader resources try { classLoader.close(); } catch (IOException e) { } // detach log file log.detachLogFile(); } private void initConfig(Config config, WFSConfig wfsConfig) { // database settings DatabaseConfig databaseConfig = config.getDatabaseConfig(); databaseConfig.setActiveConnection(wfsConfig.getDatabase().getConnection()); databaseConfig.setReferenceSystems(wfsConfig.getDatabase().getReferenceSystems()); // global settings GlobalConfig globalConfig = config.getGlobalConfig(); globalConfig.setCache(wfsConfig.getServer().getTempCache()); // export settings ExportConfig exportConfig = config.getExportConfig(); exportConfig.getContinuation().setExportCityDBMetadata(wfsConfig.getConstraints().isExportCityDBMetadata()); exportConfig.getCityObjectGroup().setExportMemberAsXLinks(true); exportConfig.getAppearances().setExportAppearances(wfsConfig.getConstraints().isExportAppearance()); if (wfsConfig.getConstraints().isExportAppearance()) { exportConfig.getAppearances().setExportTextureFiles(false); exportConfig.getAppearances().setUniqueTextureFileNames(true); exportConfig.getAppearances().getTexturePath().setUseBuckets(true); exportConfig.getAppearances().getTexturePath().setNoOfBuckets(Constants.TEXTURE_CACHE_BUCKETS); } } private void initLogging(WFSConfig wfsConfig, ServletContext context) throws ServletException { FileLog fileLog = wfsConfig.getLogging().getFile(); ConsoleLog consoleLog = wfsConfig.getLogging().getConsole(); // try and read log filename from configuration file Path logFile; if (fileLog.getFileName() != null) { logFile = Paths.get(fileLog.getFileName()); if (Files.isDirectory(logFile)) { logFile = logFile.resolve(Constants.LOG_FILE); } } else { logFile = Paths.get(Constants.LOG_FILE); } // choose default log filename if we did not succeed if (!logFile.isAbsolute()) { String logPath = context.getRealPath(Constants.LOG_PATH); if (logPath == null) { throw new ServletException("Failed to access local log path at '" + Constants.LOG_PATH + "'."); } logFile = Paths.get(logPath).resolve(logFile); } // log to console log.enableConsoleLogging(consoleLog != null); if (consoleLog != null) log.setConsoleLogLevel(consoleLog.getLogLevel()); // log to file log.setFileLogLevel(fileLog.getLogLevel()); log.appendLogFile(logFile, LogFileMode.APPEND); } }
package net.domesdaybook.matcher.sequence; import java.io.IOException; import net.domesdaybook.matcher.bytes.ByteMatcher; import net.domesdaybook.reader.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.domesdaybook.reader.Window; /** * An immutable sequence matcher which matches sequences of other sequence matchers. * For example, we could have a sequence of bytes, followed by a case insensitive * sequence, followed by a fixed gap, followed by a byte set sequence. * * @author Matt Palmer */ public final class SequenceArrayMatcher implements SequenceMatcher { private final SequenceMatcher[] matchers; private final int length; public SequenceArrayMatcher(final Collection<? extends SequenceMatcher> matchList) { this(matchList, 1); } public SequenceArrayMatcher(final Collection<? extends SequenceMatcher> matcherCollection, final int numberOfRepeats) { if (matcherCollection == null || matcherCollection.isEmpty()) { throw new IllegalArgumentException("Null or empty match list passed in to SequenceArrayMatcher."); } if (numberOfRepeats < 1) { throw new IllegalArgumentException("SequenceArrayMatcher requires a positive number of repeats."); } if (numberOfRepeats == 1) { matchers = matcherCollection.toArray(new SequenceMatcher[matcherCollection.size() * numberOfRepeats]); length = matchers.length; } else { length = matcherCollection.size() * numberOfRepeats; final List<SequenceMatcher> allMatchers = new ArrayList<SequenceMatcher>(length); for (int count = 0; count < numberOfRepeats; count++) { allMatchers.addAll(matcherCollection); } matchers = matcherCollection.toArray(new SequenceMatcher[length]); } } public SequenceArrayMatcher(final SequenceMatcher[] matchArray) { this(matchArray, 1); } public SequenceArrayMatcher(final SequenceMatcher[] matchArray, final int numberOfRepeats) { if (matchArray == null || matchArray.length == 0) { throw new IllegalArgumentException("Null or empty match array passed in to SequenceArrayMatcher."); } if (numberOfRepeats < 1) { throw new IllegalArgumentException("SequenceArrayMatcher requires a positive number of repeats."); } if (numberOfRepeats == 1) { matchers = matchArray.clone(); length = matchers.length; } else { final int numberOfMatchers = matchArray.length; length = numberOfMatchers * numberOfRepeats; matchers = new SequenceMatcher[length]; for (int repeat = 0; repeat < numberOfRepeats; repeat++) { System.arraycopy(matchArray, 0, matchers, repeat * numberOfMatchers, numberOfMatchers); } } } /** * {@inheritDoc} */ @Override public boolean matches(final Reader reader, final long matchPosition) throws IOException { final int localLength = length; final SequenceMatcher[] localArray = matchers; Window window = reader.getWindow(matchPosition); int checkPos = 0; int matchIndex = 0; while (window != null) { final int offset = reader.getWindowOffset(matchPosition + checkPos); final int endPos = Math.min(window.length(), offset + localLength - checkPos); final byte[] array = window.getArray(); while (offset + checkPos < endPos) { final SequenceMatcher matcher = localArray[matchIndex++]; final int matcherLength = matcher.length(); // If our matcher fits within the current window, check using the window: if (offset + checkPos + matcherLength <= endPos) { if (!matcher.matchesNoBoundsCheck(array, offset + checkPos)) { return false; } } else { // the matcher spans two windows, or is at the limit of the final window. if (!matcher.matches(reader, matchPosition + checkPos)) { return false; } } checkPos += matcherLength; } if (checkPos == localLength) { return true; } window = reader.getWindow(matchPosition + checkPos); } return false; } /** * {@inheritDoc} */ @Override public boolean matches(final byte[] bytes, final int matchPosition) { if (matchPosition + length < bytes.length && matchPosition >= 0) { int matchAt = matchPosition; final SequenceMatcher[] localMatchers = matchers; for (final SequenceMatcher matcher : localMatchers) { if (matcher.matchesNoBoundsCheck(bytes, matchAt)) { matchAt += matcher.length(); } else { return false; } } return true; } return false; } /** * {@inheritDoc} */ @Override public boolean matchesNoBoundsCheck(final byte[] bytes, final int matchPosition) { int matchAt = matchPosition; final SequenceMatcher[] localMatchers = matchers; for (final SequenceMatcher matcher : localMatchers) { if (matcher.matchesNoBoundsCheck(bytes, matchAt)) { matchAt += matcher.length(); } else { return false; } } return true; } /** * {@inheritDoc} */ @Override public int length() { return length; } /** * {@inheritDoc} */ @Override public String toRegularExpression(final boolean prettyPrint) { final StringBuilder regularExpression = new StringBuilder(); for (final SequenceMatcher matcher : matchers) { regularExpression.append(matcher.toRegularExpression(prettyPrint)); } return regularExpression.toString(); } /** * {@inheritDoc} */ @Override public ByteMatcher getMatcherForPosition(final int position) { if (position < 0 || position >= length) { throw new IndexOutOfBoundsException( String.format("Position %d out of bounds in sequence of length %d", position, length)); } int currentPosition = 0; for (final SequenceMatcher matcher : matchers) { final int matcherLength = matcher.length(); currentPosition += matcherLength; if (position <= currentPosition) { final int matcherOffset = position + matcherLength - currentPosition; return matcher.getMatcherForPosition(matcherOffset); } } final String badness = "A ByteMatcher for position %d in a SequenceArrayMatcher of length %d could not be retrieved. This should not happen; there is a bug. Please report this to the byteseek developers."; throw new RuntimeException(String.format(badness, position, length)); } /** * Returns an array of {@link SequenceMatcher}s this sequence array matcher matches. * * @return An array of SequenceMatchers. */ public SequenceMatcher[] getMatchers() { return matchers.clone(); } /** * {@inheritDoc} */ @Override public SequenceArrayMatcher reverse() { final SequenceMatcher[] reversed = new SequenceMatcher[matchers.length]; int position = matchers.length - 1; for (final SequenceMatcher matcher : matchers) { reversed[position--] = matcher.reverse(); } return new SequenceArrayMatcher(reversed); } /** * {@inheritDoc} */ @Override public SequenceMatcher subsequence(final int beginIndex, final int endIndex) { // Check it is a valid subsequence: if (beginIndex < 0 || endIndex > length || beginIndex >= endIndex) { final String message = "Subsequence index %d to %d is out of bounds in a sequence of length %d"; throw new IndexOutOfBoundsException(String.format(message, beginIndex, endIndex, length)); } // Locate info about the start and ending matchers for these index positions: SequenceMatcher startMatcher = null, endMatcher = null; int startOffset = 0, endLimit = 0; int startIndex = 0, lastIndex = 0; int currentPosition = 0; int startPosition = beginIndex; int endPosition = endIndex - 1; for (int matcherIndex = 0; matcherIndex < matchers.length; matcherIndex++) { final SequenceMatcher matcher = matchers[matcherIndex]; final int matcherLength = matcher.length(); currentPosition += matcherLength; if (startPosition <= currentPosition) { startMatcher = matcher; startOffset = beginIndex - (currentPosition - matcherLength); startIndex = matcherIndex; startPosition = Integer.MAX_VALUE; } if (endPosition <= currentPosition) { endMatcher = matcher; endLimit = endIndex - (currentPosition - matcherLength) + 1; lastIndex = matcherIndex; break; } } // If there's only one matcher involved, then return a subsequence of it: if (startMatcher == endMatcher) { return startMatcher.subsequence(startOffset, endLimit); } // Otherwise, get the possibly truncated start and ending matchers: final int newSize = lastIndex - startIndex + 1; final SequenceMatcher[] newSequence = new SequenceMatcher[newSize]; newSequence[0] = startMatcher.subsequence(startOffset, startMatcher.length()); newSequence[newSize - 1] = endMatcher.subsequence(0, endLimit); // Any other matchers in the middle are copied across: if (newSize > 2) { System.arraycopy(matchers, startIndex + 1, newSequence, 1, newSize - 2); } // Forming the new sequence array matcher: return new SequenceArrayMatcher(newSequence); } /** * {@inheritDoc} */ @Override public SequenceMatcher subsequence(final int beginIndex) { return subsequence(beginIndex, length()); } /** * {@inheritDoc} */ @Override public SequenceMatcher repeat(int numberOfRepeats) { if (numberOfRepeats < 1) { throw new IllegalArgumentException("Number of repeats must be at least one."); } if (numberOfRepeats == 1) { return this; } return new SequenceArrayMatcher(matchers, numberOfRepeats); } /** * Returns a string representation of this matcher. The format is subject * to change, but it will generally return the name of the matching class * and a regular expression defining the bytes matched by the matcher. * * @return A string representing this matcher. */ @Override public String toString() { return getClass().getSimpleName() + "(" + toRegularExpression(true) + ")"; } }
package openccsensors.common.sensorperipheral; import cpw.mods.fml.common.FMLCommonHandler; import openccsensors.common.core.ISensorEnvironment; import dan200.computer.api.IComputerAccess; import dan200.computer.api.IPeripheral; import net.minecraft.src.EntityPlayer; import net.minecraft.src.IInventory; import net.minecraft.src.InventoryBasic; import net.minecraft.src.ItemStack; import net.minecraft.src.NBTTagCompound; import net.minecraft.src.TileEntity; import net.minecraft.src.Vec3; import net.minecraft.src.World; public class TileEntitySensor extends TileEntity implements ISensorEnvironment, IPeripheral, IInventory { private PeripheralSensor peripheral; private IInventory inventory; public TileEntitySensor() { peripheral = new PeripheralSensor(this, false); inventory = new InventoryBasic("Sensor", 1); } public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); NBTTagCompound item = nbttagcompound.getCompoundTag("item"); inventory.setInventorySlotContents(0, ItemStack.loadItemStackFromNBT(item)); } public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); NBTTagCompound item = new NBTTagCompound(); ItemStack sensorStack = inventory.getStackInSlot(0); if( sensorStack != null ) { sensorStack.writeToNBT(item); } nbttagcompound.setTag("item", item); } // IPeripheral interface - basically a proxy to the SensorPeripheral, allowing us to reuse code for the turtle peripheral public boolean getDirectional() { return peripheral.isDirectional(); } public void setDirectional(boolean isDirectional) { peripheral.setDirectional(isDirectional); } @Override public String getType() { return peripheral.getType(); } @Override public String[] getMethodNames() { return peripheral.getMethodNames(); } @Override public Object[] callMethod(IComputerAccess computer, int method, Object[] arguments) throws Exception { return peripheral.callMethod(computer, method, arguments); } @Override public boolean canAttachToSide(int side) { return peripheral.canAttachToSide(side); } @Override public void attach(IComputerAccess computer, String computerSide) { peripheral.attach(computer, computerSide); } @Override public void detach(IComputerAccess computer) { peripheral.detach(computer); } // ISensorEnvironment interface implementation - again will allow us to work on both turtles and our own block @Override public World getWorld() { return worldObj; } @Override public Vec3 getLocation() { return Vec3.createVectorHelper( xCoord, yCoord, zCoord ); } public ItemStack getSensorCard() { return getStackInSlot(0); } // IInventory implementation - but we delegate to the BasicInventory we created @Override public int getSizeInventory() { return inventory.getSizeInventory(); } @Override public ItemStack getStackInSlot(int var1) { return inventory.getStackInSlot(var1); } @Override public ItemStack decrStackSize(int var1, int var2) { return inventory.decrStackSize(var1, var2); } @Override public ItemStack getStackInSlotOnClosing(int var1) { return inventory.getStackInSlotOnClosing(var1); } @Override public void setInventorySlotContents(int var1, ItemStack var2) { inventory.setInventorySlotContents(var1, var2); } @Override public String getInvName() { return inventory.getInvName(); } @Override public int getInventoryStackLimit() { return inventory.getInventoryStackLimit(); } @Override public boolean isUseableByPlayer(EntityPlayer var1) { return inventory.isUseableByPlayer(var1); } @Override public void openChest() {} @Override public void closeChest() {} }
package org.apache.xerces.impl.xs.traversers; import org.apache.xerces.impl.xs.SchemaGrammar; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.XSParticleDecl; import org.apache.xerces.impl.xs.XSModelGroupImpl; import org.apache.xerces.impl.xs.XSGroupDecl; import org.apache.xerces.impl.xs.XSMessageFormatter; import org.apache.xerces.util.DOMUtil; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.impl.xs.util.XInt; import org.apache.xerces.xni.QName; import org.w3c.dom.Element; /** * The model group schema component traverser. * * <group * name = NCName> * Content: (annotation?, (all | choice | sequence)) * </group> * * @author Rahul Srivastava, Sun Microsystems Inc. * @author Elena Litani, IBM * @author Lisa Martin, IBM * @version $Id$ */ class XSDGroupTraverser extends XSDAbstractParticleTraverser { XSDGroupTraverser (XSDHandler handler, XSAttributeChecker gAttrCheck) { super(handler, gAttrCheck); } XSParticleDecl traverseLocal(Element elmNode, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { // General Attribute Checking for elmNode declared locally Object[] attrValues = fAttrChecker.checkAttributes(elmNode, false, schemaDoc); QName refAttr = (QName) attrValues[XSAttributeChecker.ATTIDX_REF]; XInt minAttr = (XInt) attrValues[XSAttributeChecker.ATTIDX_MINOCCURS]; XInt maxAttr = (XInt) attrValues[XSAttributeChecker.ATTIDX_MAXOCCURS]; XSGroupDecl group = null; // ref should be here. if (refAttr == null) { reportSchemaError("s4s-att-must-appear", new Object[]{"group (local)", "ref"}, elmNode); } else { // get global decl // index is a particle index. group = (XSGroupDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.GROUP_TYPE, refAttr, elmNode); } // no children other than "annotation?" are allowed Element child = DOMUtil.getFirstChildElement(elmNode); if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(child, attrValues, false, schemaDoc); child = DOMUtil.getNextSiblingElement(child); } if (child != null) { reportSchemaError("s4s-elt-must-match", new Object[]{"group (local)", "(annotation?)"}, elmNode); } int minOccurs = minAttr.intValue(); int maxOccurs = maxAttr.intValue(); XSParticleDecl particle = null; // not empty group, not empty particle if (group != null && group.fModelGroup != null && !(minOccurs == 0 && maxOccurs == 0)) { // create a particle to contain this model group if (fSchemaHandler.fDeclPool != null) { particle = fSchemaHandler.fDeclPool.getParticleDecl(); } else { particle = new XSParticleDecl(); } particle.fType = XSParticleDecl.PARTICLE_MODELGROUP; particle.fValue = group.fModelGroup; particle.fMinOccurs = minOccurs; particle.fMaxOccurs = maxOccurs; } fAttrChecker.returnAttrArray(attrValues, schemaDoc); return particle; } // traverseLocal XSGroupDecl traverseGlobal(Element elmNode, XSDocumentInfo schemaDoc, SchemaGrammar grammar) { // General Attribute Checking for elmNode declared globally Object[] attrValues = fAttrChecker.checkAttributes(elmNode, true, schemaDoc); String strNameAttr = (String) attrValues[XSAttributeChecker.ATTIDX_NAME]; // must have a name if (strNameAttr == null) { reportSchemaError("s4s-att-must-appear", new Object[]{"group (global)", "name"}, elmNode); } XSGroupDecl group = null; XSParticleDecl particle = null; // must have at least one child Element l_elmChild = DOMUtil.getFirstChildElement(elmNode); if (l_elmChild == null) { reportSchemaError("s4s-elt-must-match", new Object[]{"group (global)", "(annotation?, (all | choice | sequence))"}, elmNode); } else { String childName = l_elmChild.getLocalName(); if (childName.equals(SchemaSymbols.ELT_ANNOTATION)) { traverseAnnotationDecl(l_elmChild, attrValues, true, schemaDoc); l_elmChild = DOMUtil.getNextSiblingElement(l_elmChild); if (l_elmChild != null) childName = l_elmChild.getLocalName(); } if (l_elmChild == null) { reportSchemaError("s4s-elt-must-match", new Object[]{"group (global)", "(annotation?, (all | choice | sequence))"}, elmNode); } else if (childName.equals(SchemaSymbols.ELT_ALL)) { particle = traverseAll(l_elmChild, schemaDoc, grammar, CHILD_OF_GROUP, null); } else if (childName.equals(SchemaSymbols.ELT_CHOICE)) { particle = traverseChoice(l_elmChild, schemaDoc, grammar, CHILD_OF_GROUP, null); } else if (childName.equals(SchemaSymbols.ELT_SEQUENCE)) { particle = traverseSequence(l_elmChild, schemaDoc, grammar, CHILD_OF_GROUP, null); } else { reportSchemaError("s4s-elt-must-match", new Object[]{"group (global)", "(annotation?, (all | choice | sequence))"}, l_elmChild); } if (l_elmChild != null && DOMUtil.getNextSiblingElement(l_elmChild) != null) { reportSchemaError("s4s-elt-must-match", new Object[]{"group (global)", "(annotation?, (all | choice | sequence))"}, DOMUtil.getNextSiblingElement(l_elmChild)); } // add global group declaration to the grammar if (strNameAttr != null) { group = new XSGroupDecl(); group.fName = strNameAttr; group.fTargetNamespace = schemaDoc.fTargetNamespace; if (particle != null) group.fModelGroup = (XSModelGroupImpl)particle.fValue; grammar.addGlobalGroupDecl(group); } } if(group != null) { // store groups redefined by restriction in the grammar so // that we can get at them at full-schema-checking time. Object redefinedGrp = fSchemaHandler.getGrpOrAttrGrpRedefinedByRestriction(XSDHandler.GROUP_TYPE, new QName(XMLSymbols.EMPTY_STRING, strNameAttr, strNameAttr, schemaDoc.fTargetNamespace), schemaDoc, elmNode); if(redefinedGrp != null) { // store in grammar grammar.addRedefinedGroupDecl(group, (XSGroupDecl)redefinedGrp, fSchemaHandler.element2Locator(elmNode)); } } fAttrChecker.returnAttrArray(attrValues, schemaDoc); return group; } // traverseGlobal }
package org.bouncycastle.math.ntru.polynomial; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A polynomial with {@link BigInteger} coefficients.<br/> * Some methods (like <code>add</code>) change the polynomial, others (like <code>mult</code>) do * not but return the result as a new polynomial. */ public class BigIntPolynomial { private final static double LOG_10_2 = Math.log10(2); BigInteger[] coeffs; /** * Constructs a new polynomial with <code>N</code> coefficients initialized to 0. * * @param N the number of coefficients */ BigIntPolynomial(int N) { coeffs = new BigInteger[N]; for (int i = 0; i < N; i++) { coeffs[i] = Constants.BIGINT_ZERO; } } /** * Constructs a new polynomial with a given set of coefficients. * * @param coeffs the coefficients */ BigIntPolynomial(BigInteger[] coeffs) { this.coeffs = coeffs; } /** * Constructs a <code>BigIntPolynomial</code> from a <code>IntegerPolynomial</code>. The two polynomials are * independent of each other. * * @param p the original polynomial */ public BigIntPolynomial(IntegerPolynomial p) { coeffs = new BigInteger[p.coeffs.length]; for (int i = 0; i < coeffs.length; i++) { coeffs[i] = BigInteger.valueOf(p.coeffs[i]); } } /** * Generates a random polynomial with <code>numOnes</code> coefficients equal to 1, * <code>numNegOnes</code> coefficients equal to -1, and the rest equal to 0. * * @param N number of coefficients * @param numOnes number of 1's * @param numNegOnes number of -1's * @return */ static BigIntPolynomial generateRandomSmall(int N, int numOnes, int numNegOnes) { List<BigInteger> coeffs = new ArrayList<BigInteger>(); for (int i = 0; i < numOnes; i++) { coeffs.add(Constants.BIGINT_ONE); } for (int i = 0; i < numNegOnes; i++) { coeffs.add(BigInteger.valueOf(-1)); } while (coeffs.size() < N) { coeffs.add(Constants.BIGINT_ZERO); } Collections.shuffle(coeffs, new SecureRandom()); BigIntPolynomial poly = new BigIntPolynomial(N); for (int i = 0; i < coeffs.size(); i++) { poly.coeffs[i] = coeffs.get(i); } return poly; } /** * Multiplies the polynomial by another, taking the indices mod N. Does not * change this polynomial but returns the result as a new polynomial.<br/> * Both polynomials must have the same number of coefficients. * * @param poly2 the polynomial to multiply by * @return a new polynomial */ public BigIntPolynomial mult(BigIntPolynomial poly2) { int N = coeffs.length; if (poly2.coeffs.length != N) { throw new IllegalArgumentException("Number of coefficients must be the same"); } BigIntPolynomial c = multRecursive(poly2); if (c.coeffs.length > N) { for (int k = N; k < c.coeffs.length; k++) { c.coeffs[k - N] = c.coeffs[k - N].add(c.coeffs[k]); } c.coeffs = Arrays.copyOf(c.coeffs, N); } return c; } /** * Karazuba multiplication */ private BigIntPolynomial multRecursive(BigIntPolynomial poly2) { BigInteger[] a = coeffs; BigInteger[] b = poly2.coeffs; int n = poly2.coeffs.length; if (n <= 1) { BigInteger[] c = coeffs.clone(); for (int i = 0; i < coeffs.length; i++) { c[i] = c[i].multiply(poly2.coeffs[0]); } return new BigIntPolynomial(c); } else { int n1 = n / 2; BigIntPolynomial a1 = new BigIntPolynomial(Arrays.copyOf(a, n1)); BigIntPolynomial a2 = new BigIntPolynomial(Arrays.copyOfRange(a, n1, n)); BigIntPolynomial b1 = new BigIntPolynomial(Arrays.copyOf(b, n1)); BigIntPolynomial b2 = new BigIntPolynomial(Arrays.copyOfRange(b, n1, n)); BigIntPolynomial A = a1.clone(); A.add(a2); BigIntPolynomial B = b1.clone(); B.add(b2); BigIntPolynomial c1 = a1.multRecursive(b1); BigIntPolynomial c2 = a2.multRecursive(b2); BigIntPolynomial c3 = A.multRecursive(B); c3.sub(c1); c3.sub(c2); BigIntPolynomial c = new BigIntPolynomial(2 * n - 1); for (int i = 0; i < c1.coeffs.length; i++) { c.coeffs[i] = c1.coeffs[i]; } for (int i = 0; i < c3.coeffs.length; i++) { c.coeffs[n1 + i] = c.coeffs[n1 + i].add(c3.coeffs[i]); } for (int i = 0; i < c2.coeffs.length; i++) { c.coeffs[2 * n1 + i] = c.coeffs[2 * n1 + i].add(c2.coeffs[i]); } return c; } } /** * Adds another polynomial which can have a different number of coefficients, * and takes the coefficient values mod <code>modulus</code>. * * @param b another polynomial */ void add(BigIntPolynomial b, BigInteger modulus) { add(b); mod(modulus); } /** * Adds another polynomial which can have a different number of coefficients. * * @param b another polynomial */ public void add(BigIntPolynomial b) { if (b.coeffs.length > coeffs.length) { int N = coeffs.length; coeffs = Arrays.copyOf(coeffs, b.coeffs.length); for (int i = N; i < coeffs.length; i++) { coeffs[i] = Constants.BIGINT_ZERO; } } for (int i = 0; i < b.coeffs.length; i++) { coeffs[i] = coeffs[i].add(b.coeffs[i]); } } /** * Subtracts another polynomial which can have a different number of coefficients. * * @param b another polynomial */ public void sub(BigIntPolynomial b) { if (b.coeffs.length > coeffs.length) { int N = coeffs.length; coeffs = Arrays.copyOf(coeffs, b.coeffs.length); for (int i = N; i < coeffs.length; i++) { coeffs[i] = Constants.BIGINT_ZERO; } } for (int i = 0; i < b.coeffs.length; i++) { coeffs[i] = coeffs[i].subtract(b.coeffs[i]); } } /** * Multiplies each coefficient by a <code>BigInteger</code>. Does not return a new polynomial but modifies this polynomial. * * @param factor */ public void mult(BigInteger factor) { for (int i = 0; i < coeffs.length; i++) { coeffs[i] = coeffs[i].multiply(factor); } } /** * Multiplies each coefficient by a <code>int</code>. Does not return a new polynomial but modifies this polynomial. * * @param factor */ void mult(int factor) { mult(BigInteger.valueOf(factor)); } /** * Divides each coefficient by a <code>BigInteger</code> and rounds the result to the nearest whole number.<br/> * Does not return a new polynomial but modifies this polynomial. * * @param divisor the number to divide by */ public void div(BigInteger divisor) { BigInteger d = divisor.add(Constants.BIGINT_ONE).divide(BigInteger.valueOf(2)); for (int i = 0; i < coeffs.length; i++) { coeffs[i] = coeffs[i].compareTo(Constants.BIGINT_ZERO) > 0 ? coeffs[i].add(d) : coeffs[i].add(d.negate()); coeffs[i] = coeffs[i].divide(divisor); } } /** * Divides each coefficient by a <code>BigDecimal</code> and rounds the result to <code>decimalPlaces</code> places. * * @param divisor the number to divide by * @param decimalPlaces the number of fractional digits to round the result to * @return a new <code>BigDecimalPolynomial</code> */ public BigDecimalPolynomial div(BigDecimal divisor, int decimalPlaces) { BigInteger max = maxCoeffAbs(); int coeffLength = (int)(max.bitLength() * LOG_10_2) + 1; // factor = 1/divisor BigDecimal factor = BigDecimal.ONE.divide(divisor, coeffLength + decimalPlaces + 1, RoundingMode.HALF_EVEN); // multiply each coefficient by factor BigDecimalPolynomial p = new BigDecimalPolynomial(coeffs.length); for (int i = 0; i < coeffs.length; i++) // multiply, then truncate after decimalPlaces so subsequent operations aren't slowed down { p.coeffs[i] = new BigDecimal(coeffs[i]).multiply(factor).setScale(decimalPlaces, RoundingMode.HALF_EVEN); } return p; } /** * Returns the base10 length of the largest coefficient. * * @return length of the longest coefficient */ public int getMaxCoeffLength() { return (int)(maxCoeffAbs().bitLength() * LOG_10_2) + 1; } private BigInteger maxCoeffAbs() { BigInteger max = coeffs[0].abs(); for (int i = 1; i < coeffs.length; i++) { BigInteger coeff = coeffs[i].abs(); if (coeff.compareTo(max) > 0) { max = coeff; } } return max; } /** * Takes each coefficient modulo a number. * * @param modulus */ void mod(BigInteger modulus) { for (int i = 0; i < coeffs.length; i++) { coeffs[i] = coeffs[i].mod(modulus); } } /** * Returns the sum of all coefficients, i.e. evaluates the polynomial at 0. * * @return the sum of all coefficients */ BigInteger sumCoeffs() { BigInteger sum = Constants.BIGINT_ZERO; for (int i = 0; i < coeffs.length; i++) { sum = sum.add(coeffs[i]); } return sum; } /** * Makes a copy of the polynomial that is independent of the original. */ public BigIntPolynomial clone() { return new BigIntPolynomial(coeffs.clone()); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(coeffs); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BigIntPolynomial other = (BigIntPolynomial)obj; if (!Arrays.equals(coeffs, other.coeffs)) { return false; } return true; } }
package org.jetbrains.plugins.scala.lang.lexer; import com.intellij.psi.tree.IElementType; public interface ScalaTokenTypes { ///////////////////////// White spaces in line ///////////////////////////////////////////////////////////////////////////////////// IElementType tWHITE_SPACE_IN_LINE = new ScalaElementType("white space in line"); ///////////////////////// White spaces in line ///////////////////////////////////////////////////////////////////////////////////// IElementType tLINE_TERMINATOR = new ScalaElementType("white space line terminate"); ///////////////////////// Stub ///////////////////////////////////////////////////////////////////////////////////// IElementType tSTUB = new ScalaElementType("stub"); ///////////////////////// Comments ///////////////////////////////////////////////////////////////////////////////////// IElementType tCOMMENT = new ScalaElementType("comment"); ///////////////////////// Strings & chars ////////////////////////////////////////////////////////////////////////////// IElementType tSTRING = new ScalaElementType("string content"); IElementType tSTRING_BEGIN = new ScalaElementType("begin of string"); IElementType tSTRING_END = new ScalaElementType("end of string"); IElementType tCHAR = new ScalaElementType("Character"); ///////////////////////// integer and float literals /////////////////////////////////////////////////////////////////// IElementType tINTEGER = new ScalaElementType("integer"); IElementType tFLOAT = new ScalaElementType("float"); ///////////////////////// Operators //////////////////////////////////////////////////////////////////////////////////// IElementType tEQUAL = new ScalaElementType("=="); IElementType tNOTEQUAL = new ScalaElementType("!="); IElementType tLESS = new ScalaElementType("<"); IElementType tLESSOREQUAL = new ScalaElementType("<="); IElementType tGREATER = new ScalaElementType(">"); IElementType tGREATEROREQUAL = new ScalaElementType(">="); IElementType tASSGN = new ScalaElementType("="); IElementType tPLUS = new ScalaElementType("+"); IElementType tMINUS = new ScalaElementType("-"); IElementType tTILDA = new ScalaElementType("~"); IElementType tNOT = new ScalaElementType("!"); IElementType tSTAR = new ScalaElementType("*"); IElementType tDIV = new ScalaElementType("/"); ///////////////////////// Braces /////////////////////////////////////////////////////////////////////////////////////// IElementType tLSQBRACKET = new ScalaElementType("["); IElementType tRSQBRACKET = new ScalaElementType("]"); IElementType tLBRACE = new ScalaElementType("{"); IElementType tRBRACE = new ScalaElementType("}"); IElementType tLPARENTHIS = new ScalaElementType("("); IElementType tRPARENTHIS = new ScalaElementType(")"); ///////////////////////// keywords ///////////////////////////////////////////////////////////////////////////////////// IElementType kABSTRACT = new ScalaElementType("abstract"); IElementType kCASE = new ScalaElementType("case"); IElementType kCATCH = new ScalaElementType("catch"); IElementType kCLASS = new ScalaElementType("class"); IElementType kDEF = new ScalaElementType("def"); IElementType kDO = new ScalaElementType("do"); IElementType kELSE = new ScalaElementType("else"); IElementType kEXTENDS = new ScalaElementType("extends"); IElementType kFALSE = new ScalaElementType("false"); IElementType kFINAL = new ScalaElementType("final"); IElementType kFINALLY = new ScalaElementType("finally"); IElementType kFOR = new ScalaElementType("for"); IElementType kIF = new ScalaElementType("if"); IElementType kIMPLICIT = new ScalaElementType("implicit"); IElementType kIMPORT = new ScalaElementType("import"); IElementType kMATCH = new ScalaElementType("match"); IElementType kNEW = new ScalaElementType("new"); IElementType kNULL = new ScalaElementType("null"); IElementType kOBJECT = new ScalaElementType("object"); IElementType kOVERRIDE = new ScalaElementType("override"); IElementType kPACKAGE = new ScalaElementType("package"); IElementType kPRIVATE = new ScalaElementType("private"); IElementType kPROTECTED = new ScalaElementType("protected"); IElementType kREQUIRES = new ScalaElementType("requires"); IElementType kRETURN = new ScalaElementType("return"); IElementType kSEALED = new ScalaElementType("sealed"); IElementType kSUPER = new ScalaElementType("super"); IElementType kTHIS = new ScalaElementType("this"); IElementType kTHROW = new ScalaElementType("throw"); IElementType kTRAIT = new ScalaElementType("trait"); IElementType kTRY = new ScalaElementType("try"); IElementType kTRUE = new ScalaElementType("true"); IElementType kTYPE = new ScalaElementType("type"); IElementType kVAL = new ScalaElementType("val"); IElementType kVAR = new ScalaElementType("var"); IElementType kWHILE = new ScalaElementType("while"); IElementType kWITH = new ScalaElementType("whith"); IElementType kYIELD = new ScalaElementType("yield"); ///////////////////////// variables and constants ////////////////////////////////////////////////////////////////////// IElementType tIDENTIFIER = new ScalaElementType("identifier"); ////////////////////////// xml tag ///////////////////////////////////////////////////////////////////////////////////// IElementType tOPENXMLTAG = new ScalaElementType("opened xml tag"); IElementType tCLOSEXMLTAG = new ScalaElementType("closed xml tag"); IElementType tBEGINSCALAEXPR = new ScalaElementType("begin of scala expression"); IElementType tENDSCALAEXPR = new ScalaElementType("end of scala expression"); IElementType tDOT = new ScalaElementType("."); IElementType tCOMMA = new ScalaElementType(","); IElementType tSEMICOLON = new ScalaElementType(";"); IElementType tUNDER = new ScalaElementType("_"); IElementType tCOLON = new ScalaElementType(":"); IElementType tASSIGN = new ScalaElementType("="); IElementType tAND = new ScalaElementType("&"); IElementType tFUNTYPE = new ScalaElementType("=>"); IElementType tFUNTYPE_ASCII = new ScalaElementType(Character.toString('\u21D2')); IElementType tCHOOSE = new ScalaElementType("<-"); IElementType tLOWER_BOUND = new ScalaElementType(">:"); IElementType tUPPER_BOUND = new ScalaElementType("<:"); IElementType tVIEW = new ScalaElementType("<%"); IElementType tINNER_CLASS = new ScalaElementType(" IElementType tAT = new ScalaElementType("@"); IElementType tQUESTION = new ScalaElementType("?"); }
package org.plantuml.idea.toolwindow; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileChooser.FileChooserFactory; import com.intellij.openapi.fileChooser.FileSaverDescriptor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileWrapper; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; import com.intellij.util.messages.MessageBus; import org.jetbrains.annotations.NotNull; import org.plantuml.idea.plantuml.PlantUml; import org.plantuml.idea.plantuml.PlantUmlResult; import org.plantuml.idea.util.LazyApplicationPoolExecutor; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import static com.intellij.codeInsight.completion.CompletionInitializationContext.DUMMY_IDENTIFIER; /** * @author Eugene Steinberg */ public class PlantUmlToolWindowFactory implements ToolWindowFactory { Logger logger = Logger.getInstance(PlantUmlToolWindowFactory.class); private Project myProject; private ToolWindow toolWindow; private JPanel mainPanel; private JLabel imageLabel; private BufferedImage diagram; private Document currentDocument; private JButton copyToClipboard; private JButton saveToFile; private FileEditorManagerListener plantUmlVirtualFileListener = new PlantUmlFileManagerListener(); private DocumentListener plantUmlDocumentListener = new PlantUmlDocumentListener(); private LazyApplicationPoolExecutor lazyExecutor = new LazyApplicationPoolExecutor(); public PlantUmlToolWindowFactory() { } public void createToolWindowContent(Project project, ToolWindow toolWindow) { myProject = project; this.toolWindow = toolWindow; createUI(); registerListeners(); renderSelectedDocument(); } private void createUI() { ContentFactory contentFactory = ContentFactory.SERVICE.getInstance(); Content content = contentFactory.createContent(mainPanel, "", false); toolWindow.getContentManager().addContent(content); copyToClipboard.addActionListener(new copyToClipboardActionListener()); saveToFile.addActionListener(new saveToFileActionListener()); } private void renderSelectedDocument() { Editor selectedTextEditor = FileEditorManager.getInstance(myProject).getSelectedTextEditor(); if (selectedTextEditor != null) { lazyRender(selectedTextEditor.getDocument()); } } private void registerListeners() { logger.debug("Registering listeners"); MessageBus messageBus = myProject.getMessageBus(); messageBus.connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, plantUmlVirtualFileListener); EditorFactory.getInstance().getEventMulticaster().addDocumentListener(plantUmlDocumentListener); } private void setDiagram(@NotNull BufferedImage image) { diagram = image; imageLabel.setIcon(new ImageIcon(diagram)); imageLabel.setPreferredSize(new Dimension(diagram.getWidth(), diagram.getHeight())); } private class PlantUmlFileManagerListener implements FileEditorManagerListener { public void fileOpened(FileEditorManager source, VirtualFile file) { logger.debug("file opened " + file); } public void fileClosed(FileEditorManager source, VirtualFile file) { logger.debug("file closed = " + file); } public void selectionChanged(FileEditorManagerEvent event) { logger.debug("selection changed" + event); VirtualFile newFile = event.getNewFile(); if (newFile != null) { Document document = FileDocumentManager.getInstance().getDocument(newFile); if (document != null) lazyRender(document); } } } private class PlantUmlDocumentListener implements DocumentListener { public void beforeDocumentChange(DocumentEvent event) { } public void documentChanged(DocumentEvent event) { logger.debug("document changed " + event); //#18 Strange "IntellijIdeaRulezzz" - filter code completion event. if (!DUMMY_IDENTIFIER.equals(event.getNewFragment().toString())) { lazyRender(event.getDocument()); } } } private void lazyRender(final Document document) { currentDocument = document; ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { final String source = document.getText(); lazyExecutor.execute(new Runnable() { public void run() { render(source); } }); } }); } private void render(String source) { PlantUmlResult result = PlantUml.render(source); try { final BufferedImage image = getBufferedImage(result.getDiagramBytes()); if (image != null) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { setDiagram(image); } }); } } catch (IOException e) { logger.warn("Exception occurred rendering source = " + source + ": " + e); } } private static BufferedImage getBufferedImage(byte[] imageBytes) throws IOException { ByteArrayInputStream input = new ByteArrayInputStream(imageBytes); return ImageIO.read(input); } private class copyToClipboardActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { CopyPasteManager.getInstance().setContents(new Transferable() { public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{ DataFlavor.imageFlavor }; } public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.equals(DataFlavor.imageFlavor); } public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (!flavor.equals(DataFlavor.imageFlavor)) { throw new UnsupportedFlavorException(flavor); } return diagram; } }); } } public static final String[] extensions; static { PlantUml.ImageFormat[] values = PlantUml.ImageFormat.values(); extensions = new String[values.length]; for (int i = 0; i < values.length; i++) { extensions[i] = values[i].toString().toLowerCase(); } } private class saveToFileActionListener implements ActionListener { public static final String FILENAME = "diagram"; public void actionPerformed(ActionEvent e) { FileOutputStream os = null; FileSaverDescriptor fsd = new FileSaverDescriptor("Save diagram", "Please choose where to save diagram", extensions); final VirtualFileWrapper wrapper = FileChooserFactory.getInstance().createSaveFileDialog( fsd, myProject).save(null, FILENAME); if (wrapper != null) { try { File file = wrapper.getFile(); String name = file.getName(); String extension = name.substring(name.lastIndexOf('.') + 1); PlantUml.ImageFormat imageFormat; try { imageFormat = PlantUml.ImageFormat.valueOf(extension.toUpperCase()); } catch (Exception e3) { throw new IOException("Extension '" + extension + "' is not supported"); } PlantUmlResult result = PlantUml.render(currentDocument.getText(), imageFormat); os = new FileOutputStream(file); os.write(result.getDiagramBytes()); os.flush(); } catch (IOException e1) { String title = "Error writing diagram"; String message = title + " to file:" + wrapper.getFile() + " : " + e1.toString(); logger.warn(message); Messages.showErrorDialog(message, title); } finally { try { if (os != null) os.close(); } catch (IOException e1) { // do nothing } } } } } }
package org.usfirst.frc2832.Robot2017.autonCommands; import java.util.ArrayList; import org.usfirst.frc2832.Robot2017.commands.gearunload.CloseDoors; import org.usfirst.frc2832.Robot2017.commands.gearunload.ExpelGear; import edu.wpi.first.wpilibj.command.Command; //helper class to read the SendableChooser inputs and eventually start autonomous public class ParseInput { static ArrayList<Command> auto_Commands; public static ArrayList<Command> takeInput(String movement) { auto_Commands = new ArrayList<Command>(0); if(movement.charAt(0) == 'f') auto_Commands.add(new DriveForward(Double.valueOf(movement.substring(1)))); //use for expelling the gear from the middle position for practice bot. VALUES HAVE BEEN TESTED else if(movement.charAt(0) == 'e'){ auto_Commands.add(new DriveForward(3.65));//Double.valueOf(movement.substring(1)))); auto_Commands.add(new ExpelGear()); auto_Commands.add(new DriveBackward(2)); auto_Commands.add(new CloseDoors()); } //use for driving forward from right or left position from practice bot. VALUES HAVE BEEN TESTED else if (movement.charAt(0) == 'c'){ auto_Commands.add(new DriveForward(4.5)); } //use for driving forward and turning from left position on practice bot. VALUES MUST BE CHECKED WITH IRON HORSE else if (movement.charAt(0) == 'h'){ auto_Commands.add(new DriveForward(3.8)); auto_Commands.add(new TurnRight(.35)); auto_Commands.add(new DriveForward(3.1)); auto_Commands.add(new ExpelGear()); auto_Commands.add(new DriveBackward(2)); auto_Commands.add(new CloseDoors()); } //use for driving forward and turning from right position on practice bot. VALUES MUST BE CHECKED WITH IRON HORSE else if (movement.charAt(0) == 'i'){ auto_Commands.add(new DriveForward(3.7)); auto_Commands.add(new TurnLeft(.5)); auto_Commands.add(new DriveForward(2.9)); auto_Commands.add(new ExpelGear()); auto_Commands.add(new DriveBackward(2)); auto_Commands.add(new CloseDoors()); } //use for driving forward from right or left position from actual bot. THESE VALUE HAVE BEEN TESTED else if (movement.charAt(0) == 'b'){ auto_Commands.add(new DriveForward(3.8)); } //use for driving forward and turning from right position on actual bot. VALUES MUST BE CHECKED WITH IRON KRAKEN else if (movement.charAt(0) == 'a'){ auto_Commands.add(new DriveForward(3.8)); auto_Commands.add(new TurnLeft(.35)); auto_Commands.add(new DriveForward(3.1)); auto_Commands.add(new ExpelGear()); auto_Commands.add(new DriveBackward(2)); auto_Commands.add(new CloseDoors()); } //use for driving forward and turning from left position on actual bot. VALUES MUST BE CHECKED WITH IRON KRAKEN else if (movement.charAt(0) == 'g'){ auto_Commands.add(new DriveForward(3.8)); auto_Commands.add(new TurnRight(.35)); auto_Commands.add(new DriveForward(3.1)); auto_Commands.add(new ExpelGear()); auto_Commands.add(new DriveBackward(2)); auto_Commands.add(new CloseDoors()); } //use for expelling the gear from the middle position of the actual bot THESE VALUES HAVE BEEN TESTED else if (movement.charAt(0) == 'd'){ auto_Commands.add(new DriveForward(3.4)); auto_Commands.add(new ExpelGear()); auto_Commands.add(new DriveBackward(1)); auto_Commands.add(new CloseDoors()); //auto_Commands.add(new AutonAimGear()); //auto_Commands.add(new ExpelGear()); //auto_Commands.add(new DriveBackward(Double.valueOf(movement.substring(2)))); } return auto_Commands; //an arraylist of the commands to be executed in autonomous } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc330.Beachbot2013Java.commands; import edu.wpi.first.wpilibj.command.AutoSpreadsheetCommand; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc330.Beachbot2013Java.Robot; public class DriveTime extends AutoSpreadsheetCommand { double left, right; public DriveTime(double timeout, double left, double right) { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.chassis); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES setTimeout(timeout); this.left = left; this.right = right; } public DriveTime() { this(0,0,0); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Robot.chassis.tankDrive(-left, -right); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return isTimedOut(); } // Called once after isFinished returns true protected void end() { Robot.chassis.tankDrive(0, 0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } public void setParam1(double left) { this.left = left; } public void setParam2(double right) { this.right = right; } public void setParam3(double param3) { } public void setStopAtEnd(boolean stopAtEnd) { } public AutoSpreadsheetCommand copy() { return new DriveTime(); } }
package org.openspaces.pu.service; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * A simple implementation of {@link ServiceMonitors}. * * @author kimchy */ public class PlainServiceMonitors implements ServiceMonitors, Externalizable { private static final long serialVersionUID = 1L; protected String id; protected ServiceDetails details; protected Map<String, Object> monitors; // Just for externalizable public PlainServiceMonitors() { } public PlainServiceMonitors(String id) { this.id = id; this.monitors = new LinkedHashMap<String, Object>(); } public String getId() { return this.id; } public Map<String, Object> getMonitors() { return this.monitors; } public ServiceDetails getDetails() { return details; } public void setDetails(ServiceDetails details) { this.details = details; } public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(id); if (monitors == null) { out.writeInt(0); } else { out.writeInt(monitors.size()); for (Map.Entry<String, Object> entry : monitors.entrySet()) { out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { id = in.readUTF(); int attributesSize = in.readInt(); if (attributesSize == 0) { monitors = Collections.EMPTY_MAP; } else { monitors = new LinkedHashMap<String, Object>(); for (int i = 0; i < attributesSize; i++) { String key = (String) in.readObject(); Object value = in.readObject(); monitors.put(key, value); } } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("id[").append(id).append("] "); for (Map.Entry<String, Object> entry : monitors.entrySet()) { sb.append(entry.getKey()).append("[").append(entry.getValue()).append("] "); } return sb.toString(); } }
package net.java.sip.communicator.impl.gui.main.menus; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.main.*; import net.java.sip.communicator.impl.gui.main.contactlist.*; import net.java.sip.communicator.impl.gui.main.contactlist.addcontact.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.gui.event.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.*; /** * The <tt>QuickMenu</tt> is the toolbar on the top of the main * application window. It provides quick access to the "User info" window, the * "Configuration" window, the "Add contact" window and the "Hide/Open offline * contacts" window. * <p> * Note that this class implements the <tt>PluginComponentListener</tt>. This * means that this toolbar is a plugable container and could contain plugin * components. * * @author Yana Stamcheva */ public class QuickMenu extends SIPCommToolBar implements ActionListener, PluginComponentListener, ComponentListener, ListSelectionListener { private Logger logger = Logger.getLogger(QuickMenu.class.getName()); private JButton infoButton = new JButton(new ImageIcon(ImageLoader .getImage(ImageLoader.QUICK_MENU_INFO_ICON))); private JButton configureButton = new JButton(new ImageIcon(ImageLoader .getImage(ImageLoader.QUICK_MENU_CONFIGURE_ICON))); private JButton searchButton = new JButton(new ImageIcon(ImageLoader .getImage(ImageLoader.QUICK_MENU_SHOW_OFFLINE_ICON))); private JButton addButton = new JButton(new ImageIcon(ImageLoader .getImage(ImageLoader.QUICK_MENU_ADD_ICON))); private JButton soundButton = new JButton( new ImageIcon(ImageLoader.getImage(ImageLoader.QUICK_MENU_SOUND_ON_ICON))); private ConfigurationManager configDialog; private MainFrame mainFrame; private int movedDownButtons = 0; /** * Create an instance of the <tt>QuickMenu</tt>. * @param mainFrame The parent <tt>MainFrame</tt> window. */ public QuickMenu(MainFrame mainFrame) { this.mainFrame = mainFrame; this.setRollover(true); this.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 0)); this.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5)); this.setFloatable(true); this.infoButton.setPreferredSize(new Dimension(28, 28)); this.configureButton.setPreferredSize(new Dimension(28, 28)); this.searchButton.setPreferredSize(new Dimension(28, 28)); this.addButton.setPreferredSize(new Dimension(28, 28)); this.soundButton.setPreferredSize(new Dimension(28, 28)); this.infoButton.setToolTipText( Messages.getI18NString("userInfo").getText()); this.configureButton.setToolTipText( Messages.getI18NString("configure").getText()); this.searchButton.setToolTipText( Messages.getI18NString("showOfflineUsers").getText()); this.addButton.setToolTipText( Messages.getI18NString("addContact").getText()); this.addButton.setToolTipText( Messages.getI18NString("soundOnOff").getText()); this.updateMuteButton( GuiActivator.getAudioNotifier().isMute()); this.init(); } /** * Initialize the <tt>QuickMenu</tt> by adding the buttons. */ private void init() { this.add(addButton); this.add(configureButton); this.add(infoButton); this.add(searchButton); this.add(soundButton); this.addButton.setName("add"); this.configureButton.setName("config"); this.searchButton.setName("search"); this.infoButton.setName("info"); this.soundButton.setName("sound"); this.addButton.addActionListener(this); this.configureButton.addActionListener(this); this.searchButton.addActionListener(this); this.infoButton.addActionListener(this); this.soundButton.addActionListener(this); this.addButton.addComponentListener(this); this.configureButton.addComponentListener(this); this.searchButton.addComponentListener(this); this.infoButton.addComponentListener(this); this.soundButton.addComponentListener(this); } private void initPluginComponents() { Iterator pluginComponents = GuiActivator.getUIService() .getComponentsForContainer( UIService.CONTAINER_MAIN_TOOL_BAR); if(pluginComponents.hasNext()) this.addSeparator(); while (pluginComponents.hasNext()) { Component c = (Component)pluginComponents.next(); this.add(c); if (c instanceof ContactAwareComponent) { Object selectedValue = mainFrame.getContactListPanel() .getContactList().getSelectedValue(); if(selectedValue instanceof MetaContact) { ((ContactAwareComponent)c) .setCurrentContact((MetaContact)selectedValue); } else if(selectedValue instanceof MetaContactGroup) { ((ContactAwareComponent)c) .setCurrentContactGroup((MetaContactGroup)selectedValue); } } } } /** * Handles the <tt>ActionEvent</tt> triggered when user clicks on one of * the buttons in this toolbar. */ public void actionPerformed(ActionEvent e) { JButton button = (JButton) e.getSource(); String buttonName = button.getName(); if (buttonName.equals("add")) { AddContactWizard wizard = new AddContactWizard(mainFrame); wizard.showDialog(false); } else if (buttonName.equals("config")) { configDialog = GuiActivator.getUIService().getConfigurationManager(); configDialog.showWindow(); } else if (buttonName.equals("search")) { ContactList contactList = mainFrame.getContactListPanel() .getContactList(); ContactListModel listModel = (ContactListModel) contactList.getModel(); Object selectedObject = null; int currentlySelectedIndex = contactList.getSelectedIndex(); if(currentlySelectedIndex != -1) { selectedObject = listModel.getElementAt(currentlySelectedIndex); } listModel.setShowOffline(!listModel.showOffline()); if (selectedObject != null) { if (selectedObject instanceof MetaContact) { contactList.setSelectedIndex( listModel.indexOf((MetaContact) selectedObject)); } else { contactList.setSelectedIndex( listModel.indexOf( (MetaContactGroup) selectedObject)); } } } else if (buttonName.equals("info")) { MetaContact selectedMetaContact = (MetaContact) mainFrame.getContactListPanel() .getContactList().getSelectedValue(); if(selectedMetaContact != null) { OperationSetWebContactInfo wContactInfo = null; Iterator protocolContacts = selectedMetaContact.getContacts(); while(protocolContacts.hasNext()) { Contact protoContact = (Contact) protocolContacts.next(); wContactInfo = mainFrame.getWebContactInfo( protoContact.getProtocolProvider()); if(wContactInfo != null) break; } if(wContactInfo != null) { Contact defaultContact = selectedMetaContact .getDefaultContact(); CrossPlatformBrowserLauncher.openURL( wContactInfo.getWebContactInfo(defaultContact) .toString()); } else { new ErrorDialog(mainFrame, Messages.getI18NString("selectContactSupportingInfo") .getText(), Messages.getI18NString("warning").getText(), ErrorDialog.WARNING).showDialog(); } } } else if (buttonName.equals("sound")) { if(GuiActivator.getAudioNotifier().isMute()) { updateMuteButton(false); GuiActivator.getAudioNotifier().setMute(false); } else { updateMuteButton(true); GuiActivator.getAudioNotifier().setMute(true); } } } /** * Implements the <code>PluginComponentListener.pluginComponentAdded</code> * method. */ public void pluginComponentAdded(PluginComponentEvent event) { Component c = (Component) event.getSource(); this.add(c); if (c instanceof ContactAwareComponent) { Object selectedValue = mainFrame.getContactListPanel() .getContactList().getSelectedValue(); if(selectedValue instanceof MetaContact) { ((ContactAwareComponent)c) .setCurrentContact((MetaContact)selectedValue); } else if(selectedValue instanceof MetaContactGroup) { ((ContactAwareComponent)c) .setCurrentContactGroup((MetaContactGroup)selectedValue); } } } /** * Implements the <code>PluginComponentListener.pluginComponentRemoved</code> * method. */ public void pluginComponentRemoved(PluginComponentEvent event) { Component c = (Component) event.getSource(); this.remove(c); } public void componentHidden(ComponentEvent e) {} /** * Implements ComponentListener.componentMoved method in order to resize * the toolbar when buttons are aligned on more than one row. */ public void componentMoved(ComponentEvent e) { int compCount = this.getComponentCount(); int buttonHeight = this.infoButton.getHeight(); int biggestY = 0; for (int i = 0; i < compCount; i ++) { Component c = this.getComponent(i); if(c instanceof JButton) { if(c.getY() > biggestY) biggestY = c.getY(); } } this.setPreferredSize( new Dimension(this.getWidth(), biggestY + buttonHeight)); ((JPanel)this.getParent()).revalidate(); ((JPanel)this.getParent()).repaint(); } public void componentResized(ComponentEvent e) {} public void componentShown(ComponentEvent e) {} public void valueChanged(ListSelectionEvent e) { if((e.getFirstIndex() != -1 || e.getLastIndex() != -1)) { Iterator pluginComponents = GuiActivator.getUIService() .getComponentsForContainer( UIService.CONTAINER_MAIN_TOOL_BAR); while (pluginComponents.hasNext()) { Component c = (Component)pluginComponents.next(); if(!(c instanceof ContactAwareComponent)) continue; Object selectedValue = mainFrame.getContactListPanel() .getContactList().getSelectedValue(); if(selectedValue instanceof MetaContact) { ((ContactAwareComponent)c) .setCurrentContact((MetaContact)selectedValue); } else if(selectedValue instanceof MetaContactGroup) { ((ContactAwareComponent)c) .setCurrentContactGroup( (MetaContactGroup)selectedValue); } } } } public void updateMuteButton(boolean isMute) { if(!isMute) this.soundButton.setIcon( new ImageIcon(ImageLoader.getImage( ImageLoader.QUICK_MENU_SOUND_ON_ICON))); else this.soundButton.setIcon( new ImageIcon(ImageLoader.getImage( ImageLoader.QUICK_MENU_SOUND_OFF_ICON))); } }
package org.texastorque.texastorque2015.feedback; import edu.wpi.first.wpilibj.CounterBase; import edu.wpi.first.wpilibj.DigitalInput; import org.texastorque.texastorque2015.constants.Ports; import org.texastorque.torquelib.component.TorqueEncoder; import org.texastorque.torquelib.component.TorqueGyro; public class SensorFeedback extends Feedback { //Drivebase private TorqueEncoder leftDriveEncoder; private TorqueEncoder rightDriveEncoder; //Elevator private TorqueEncoder elevatorEncoder; private DigitalInput topLimit; private DigitalInput bottomLimit; //Sluice private DigitalInput sluiceLimitSwitch; //Angle private TorqueGyro gyro; public SensorFeedback() { leftDriveEncoder = new TorqueEncoder(Ports.LEFT_ENCODER_PORT_A, Ports.LEFT_ENCODER_PORT_B, true, CounterBase.EncodingType.k2X); rightDriveEncoder = new TorqueEncoder(Ports.RIGHT_ENCODER_PORT_A, Ports.RIGHT_ENCODER_PORT_B, false, CounterBase.EncodingType.k2X); elevatorEncoder = new TorqueEncoder(Ports.ELEVATOR_ENCODER_PORT_A, Ports.ELEVATOR_ENCODER_PORT_B, false, CounterBase.EncodingType.k4X); topLimit = new DigitalInput(Ports.ELEVATOR_TOP_LIMIT); bottomLimit = new DigitalInput(Ports.ELEVATOR_BOTTOM_LIMIT); sluiceLimitSwitch = new DigitalInput(Ports.SLUICE_BUTTON); gyro = new TorqueGyro(Ports.GYRO_PORT_A, Ports.GYRO_PORT_B); } @Override public void run() { //Drivebase //Units use feet and seconds. leftDriveEncoder.calc(); rightDriveEncoder.calc(); leftDrivePosition = leftDriveEncoder.get() * 0.0062831853;//250 clicks/rot & 6 in diam rightDrivePosition = rightDriveEncoder.get() * 0.0062831853; leftDriveVelocity = leftDriveEncoder.getRate() * 0.0062831853; rightDriveVelocity = rightDriveEncoder.getRate() * 0.0062831853; leftDriveAcceleration = leftDriveEncoder.getAcceleration() * 0.0062831853; rightDriveAcceleration = rightDriveEncoder.getAcceleration() * 0.0062831853; //Elevator elevatorEncoder.calc(); elevatorHeight = elevatorEncoder.get() * 0.0225; //Put in conversion elevatorVelocity = elevatorEncoder.getRate() * 0.0225; //Put in conversion elevatorAtTop = topLimit.get(); elevatorAtBottom = bottomLimit.get(); //Sluice toteInSluice = topLimit.get(); //angle (radians) angle = gyro.getAngle(); angularVelocity = gyro.getRate(); } @Override public void resetDriveEncoders() { leftDriveEncoder.reset(); rightDriveEncoder.reset(); } @Override public void resetGyro() { gyro.reset(); } }
package org.vitrivr.cineast.core.features; import org.vitrivr.cineast.core.config.ReadableQueryConfig; import org.vitrivr.cineast.core.data.segments.SegmentContainer; import org.vitrivr.cineast.core.features.abstracts.SolrTextRetriever; public class DescriptionTextSearch extends SolrTextRetriever { public static final String DESCRIPTION_TEXT_TABLE_NAME = "features_captioning"; /** * Default constructor for {@link DescriptionTextSearch} */ public DescriptionTextSearch() { super(DESCRIPTION_TEXT_TABLE_NAME); } @Override public void processSegment(SegmentContainer shot) { /* TODO: Not implemented because densecap extraction is not integrated into pipeline yet. */ } @Override protected String[] generateQuery(SegmentContainer sc, ReadableQueryConfig qc) { return sc.getText().split(" "); } }
package gw.internal.gosu.parser; import gw.lang.reflect.IDynamicType; import gw.internal.gosu.parser.expressions.BlockType; import gw.internal.gosu.parser.expressions.TypeVariableDefinition; import gw.internal.gosu.parser.expressions.TypeVariableDefinitionImpl; import gw.lang.Gosu; import gw.lang.parser.AsmTypeVarMatcher; import gw.lang.parser.GosuParserFactory; import gw.lang.parser.GosuParserTypes; import gw.lang.parser.IExpression; import gw.lang.parser.IScriptPartId; import gw.lang.parser.ITypeUsesMap; import gw.lang.parser.RawTypeVarMatcher; import gw.lang.parser.ScriptabilityModifiers; import gw.lang.parser.StandardCoercionManager; import gw.lang.parser.StandardSymbolTable; import gw.lang.parser.TypeSystemAwareCache; import gw.lang.parser.TypeVarToTypeMap; import gw.lang.parser.coercers.FunctionToInterfaceCoercer; import gw.lang.parser.exceptions.ParseResultsException; import gw.lang.parser.expressions.ITypeLiteralExpression; import gw.lang.parser.expressions.ITypeVariableDefinition; import gw.lang.parser.expressions.Variance; import gw.lang.reflect.FunctionType; import gw.lang.reflect.IBlockType; import gw.lang.reflect.IErrorType; import gw.lang.reflect.IFunctionType; import gw.lang.reflect.IMetaType; import gw.lang.reflect.INonLoadableType; import gw.lang.reflect.IPlaceholder; import gw.lang.reflect.IType; import gw.lang.reflect.ITypeLoader; import gw.lang.reflect.ITypeVariableArrayType; import gw.lang.reflect.ITypeVariableType; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.gs.IGenericTypeVariable; import gw.lang.reflect.gs.IGosuClass; import gw.lang.reflect.gs.IGosuProgram; import gw.lang.reflect.java.IJavaClassInfo; import gw.lang.reflect.java.IJavaType; import gw.lang.reflect.java.JavaTypes; import gw.lang.reflect.java.asm.AsmClass; import gw.lang.reflect.java.asm.AsmPrimitiveType; import gw.lang.reflect.java.asm.AsmType; import gw.lang.reflect.java.asm.AsmWildcardType; import gw.lang.reflect.java.asm.IAsmType; import gw.lang.reflect.module.IModule; import gw.util.GosuObjectUtil; import gw.util.Pair; import gw.util.concurrent.Cache; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.function.Predicate; public class TypeLord { // LRUish cache of assignability results (recent tests indicate 99% hit rates) private static final TypeSystemAwareCache<Pair<IType, IType>, Boolean> ASSIGNABILITY_CACHE = TypeSystemAwareCache.make( "Assignability Cache", getAssignabilityCacheSize(), new Cache.MissHandler<Pair<IType, IType>, Boolean>() { public final Boolean load( Pair<IType, IType> key ) { return areGenericOrParameterizedTypesAssignableInternal( key.getFirst(), key.getSecond() ); } } ); private static final int DEFAULT_ASSIGNABILITY_CACHE_SIZE = 1000; private static int getAssignabilityCacheSize() { try { String assignabilityCacheSize = System.getProperty("assignabilityCacheSize"); if (assignabilityCacheSize != null) { return Math.max(Integer.valueOf(assignabilityCacheSize), DEFAULT_ASSIGNABILITY_CACHE_SIZE); } } catch (Exception e) { new RuntimeException("Unable to set value of assignability cache due to an exception, the default value will be used", e).printStackTrace(); } return DEFAULT_ASSIGNABILITY_CACHE_SIZE; } public static Set<IType> getAllClassesInClassHierarchyAsIntrinsicTypes( IJavaClassInfo cls ) { Set<IJavaClassInfo> classSet = new HashSet<IJavaClassInfo>(); addAllClassesInClassHierarchy( cls, classSet ); Set<IType> intrinsicTypeSet = new HashSet<IType>(); intrinsicTypeSet.add(JavaTypes.OBJECT()); for(IJavaClassInfo classInfo : classSet) { intrinsicTypeSet.add( classInfo.getJavaType() ); } return intrinsicTypeSet; } public static Set<IType> getAllClassesInClassHierarchyAsIntrinsicTypes( IType type ) { HashSet<IType> typeSet = new HashSet<IType>(); addAllClassesInClassHierarchy( type, typeSet ); return typeSet; } public static boolean encloses( IType type, IType inner ) { return inner != null && (inner.getEnclosingType() == type || encloses( type, inner.getEnclosingType() )); } public static boolean enclosingTypeInstanceInScope( IType type, IGosuClassInternal inner ) { return inner != null && !inner.isStatic() && ((type != null && type.isAssignableFrom( inner.getEnclosingType() )) || enclosingTypeInstanceInScope( type, (IGosuClassInternal)inner.getEnclosingType() )); } public static Set<IType> getArrayVersionsOfEachType( Set componentTypes ) { Set<IType> allTypes = new HashSet<IType>(); allTypes.add( JavaTypes.OBJECT() ); Iterator it = componentTypes.iterator(); while( it.hasNext() ) { IType type = (IType)it.next(); allTypes.add( type.getArrayType() ); } return allTypes; } public static IType getActualType( Type type, TypeVarToTypeMap actualParamByVarName ) { return getActualType( type, actualParamByVarName, false ); } public static IType getActualType( Type type, TypeVarToTypeMap actualParamByVarName, boolean bKeepTypeVars ) { return getActualType( type, actualParamByVarName, bKeepTypeVars, new LinkedHashSet<Type>() ); } public static IType getActualType( Type type, TypeVarToTypeMap actualParamByVarName, boolean bKeepTypeVars, LinkedHashSet<Type> recursiveTypes ) { IType retType; if( type instanceof Class ) { retType = TypeSystem.get( (Class)type ); } else if( type instanceof TypeVariable ) { retType = actualParamByVarName.getByMatcher( (TypeVariable)type, RawTypeVarMatcher.instance() ); if( retType == null ) { // the type must come from the map, otherwise it comes from a context where there is no argument for the type var, hence the error type return ErrorType.getInstance( ((TypeVariable)type).getName() ); } if( bKeepTypeVars && retType instanceof ITypeVariableType && ((TypeVariable)type).getName().equals( retType.getName() ) && ((ITypeVariableType)retType).getBoundingType() != null ) { IType boundingType = ((ITypeVariableType)retType).getBoundingType(); IType actualBoundingType = getActualType( boundingType, actualParamByVarName, bKeepTypeVars ); if( !actualBoundingType.getName().equals( boundingType.toString() ) ) { ITypeVariableDefinition typeVarDef = ((ITypeVariableType)retType).getTypeVarDef(); if( typeVarDef instanceof TypeVariableDefinition ) { typeVarDef = ((TypeVariableDefinition)typeVarDef).getTypeVarDef(); } TypeVariableDefinitionImpl tvd = ((TypeVariableDefinitionImpl)typeVarDef).clone( actualBoundingType ); retType = new TypeVariableType( tvd, ((ITypeVariableType)retType).getTypeVarDef().getEnclosingType() instanceof IFunctionType ); } } else if( !bKeepTypeVars ) { retType = getDefaultParameterizedTypeWithTypeVars( retType ); } } else if( type instanceof WildcardType ) { Type bound = ((WildcardType)type).getUpperBounds()[0]; Type lowerBound = maybeGetLowerBound( (WildcardType)type, actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( lowerBound != null ) { bound = lowerBound; } retType = getActualType( bound, actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( retType instanceof TypeVariableType ) { ITypeVariableDefinition tvd = ((ITypeVariableType)retType).getTypeVarDef().clone(); retType = new TypeVariableType( tvd, ((ITypeVariableType)retType).isFunctionStatement() ); ((TypeVariableType)retType).getTypeVarDef().setVariance( ((WildcardType)type).getLowerBounds().length == 0 ? Variance.WILD_COVARIANT : Variance.WILD_CONTRAVARIANT ); } } else if( type instanceof ParameterizedType ) { recursiveTypes.add( type ); try { IType genType = getActualType( ((ParameterizedType)type).getRawType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ); Type[] typeArgs = ((ParameterizedType)type).getActualTypeArguments(); if( typeArgs == null || typeArgs.length == 0 ) { retType = genType; } else { IType[] types = new IType[typeArgs.length]; for( int i = 0; i < types.length; i++ ) { Type typeArg = typeArgs[i]; if( !bKeepTypeVars && typeArg instanceof TypeVariable ) { Type bound = ((TypeVariable)typeArg).getBounds()[0]; if( !recursiveTypes.contains( bound ) ) { types[i] = getActualType( bound, actualParamByVarName, bKeepTypeVars, recursiveTypes ); } else if( bound instanceof ParameterizedType ) { types[i] = getActualType( ((ParameterizedType)bound).getRawType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ); } else { throw new IllegalStateException( "Expecting bound to be a ParameterizedType here" ); } } else { if( typeArg instanceof WildcardType && (((WildcardType)typeArg).getUpperBounds()[0].equals( Object.class ) || ((WildcardType)typeArg).getLowerBounds().length > 0) ) { Type lowerBound = maybeGetLowerBound( (WildcardType)typeArg, actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( lowerBound == null ) { // Object is the default type for the naked <?> wildcard, so we have to get the actual bound, if different, from the corresponding type var Type[] boundingTypes = ((Class)((ParameterizedType)type).getRawType()).getTypeParameters()[i].getBounds(); Type boundingType = boundingTypes.length == 0 ? null : boundingTypes[0]; if( boundingType != null ) { typeArg = boundingType; } } } types[i] = getActualType( typeArg, actualParamByVarName, bKeepTypeVars, recursiveTypes ); } } retType = genType.getParameterizedType( types ); } } finally { recursiveTypes.remove( type ); } } else if( type instanceof GenericArrayType ) { retType = getActualType( ((GenericArrayType)type).getGenericComponentType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ).getArrayType(); } else { //retType = parseType( normalizeJavaTypeName( type ), actualParamByVarName, bKeepTypeVars, null ); throw new IllegalStateException(); } return retType; } private static Type maybeGetLowerBound( WildcardType type, TypeVarToTypeMap actualParamByVarName, boolean bKeepTypeVars, LinkedHashSet<Type> recursiveTypes ) { Type[] lowers = type.getLowerBounds(); if( lowers != null && lowers.length > 0 && recursiveTypes.size() > 0 ) { // This is a "super" (contravariant) wildcard LinkedList<Type> list = new LinkedList<>( recursiveTypes ); Type enclType = list.getLast(); if( enclType instanceof ParameterizedType ) { IType genType = getActualType( ((ParameterizedType)enclType).getRawType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( genType instanceof IJavaType ) { if( FunctionToInterfaceCoercer.getSingleMethodFromJavaInterface( (IJavaType)genType ) != null ) { // For functional interfaces we keep the lower bound as an upper bound so that blocks maintain contravariance wrt the single method's parameters return lowers[0]; } } } } return null; } public static IType getActualType( IAsmType type, TypeVarToTypeMap actualParamByVarName ) { return getActualType( type, actualParamByVarName, false, new LinkedHashSet<IAsmType>() ); } public static IType getActualType( IAsmType type, TypeVarToTypeMap actualParamByVarName, boolean bKeepTypeVars, LinkedHashSet<IAsmType> recursiveTypes ) { if( type instanceof AsmClass ) { return TypeSystem.getByFullNameIfValid( type.getName() ); } if( type instanceof AsmPrimitiveType ) { return JavaType.getPrimitiveType( type.getName() ); } if( type.isArray() ) { return getActualType( type.getComponentType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ).getArrayType(); } if( type.isTypeVariable() ) { IType retType = actualParamByVarName.getByMatcher( type, AsmTypeVarMatcher.instance() ); if( retType == null ) { // the type must come from the map, otherwise it comes from a context where there is no argument for the type var, hence the error type retType = ErrorType.getInstance( type.getName() ); } if( bKeepTypeVars && retType instanceof ITypeVariableType && type.getName().equals( retType.getName() ) && ((ITypeVariableType)retType).getBoundingType() != null ) { IType boundingType = ((ITypeVariableType)retType).getBoundingType(); IType actualBoundingType = getActualType( boundingType, actualParamByVarName, bKeepTypeVars ); if( !actualBoundingType.getName().equals( boundingType.getName() ) ) { TypeVariableDefinitionImpl tvd = ((TypeVariableDefinitionImpl)((ITypeVariableType)retType).getTypeVarDef()).clone( actualBoundingType ); retType = new TypeVariableType( tvd, type instanceof AsmType && ((AsmType)type).isFunctionTypeVariable() ); } } else if( !bKeepTypeVars ) { retType = getDefaultParameterizedTypeWithTypeVars( retType ); } return retType; } else if( type instanceof AsmWildcardType ) { AsmType bound = ((AsmWildcardType)type).getBound(); if( bound != null && !((AsmWildcardType)type).isCovariant() && recursiveTypes.size() > 0 ) { LinkedList<IAsmType> list = new LinkedList<>( recursiveTypes ); IAsmType enclType = list.getLast(); List<AsmType> typeArgs = enclType.getTypeParameters(); if( typeArgs != null && typeArgs.size() > 0 ) { IType genType = TypeSystem.getByFullNameIfValid( enclType.getRawType().getName() ); if( genType instanceof IJavaType ) { // For functional interfaces we keep the lower bound as an upper bound so that blocks maintain contravariance wrt the single method's parameters if( FunctionToInterfaceCoercer.getSingleMethodFromJavaInterface( (IJavaType)genType ) == null ) { bound = null; } } } } if( bound == null ) { return JavaTypes.OBJECT(); } IType actualType = getActualType( bound, actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( actualType instanceof TypeVariableType ) { ITypeVariableDefinition tvd = ((ITypeVariableType)actualType).getTypeVarDef().clone(); actualType = new TypeVariableType( tvd, bound.isFunctionTypeVariable() ); ((TypeVariableType)actualType).getTypeVarDef().setVariance( ((AsmWildcardType)type).isCovariant() ? Variance.WILD_COVARIANT : Variance.WILD_CONTRAVARIANT ); } return actualType; } else if( type instanceof AsmType ) { List<AsmType> typeArgs = type.getTypeParameters(); if( typeArgs == null || typeArgs.size() == 0 ) { return TypeSystem.getByFullNameIfValid( type.getName() ); } else { recursiveTypes.add( type ); try { List<IType> types = new ArrayList<IType>( typeArgs.size() ); for( int i = 0; i < typeArgs.size(); i++ ) { AsmType typeArg = typeArgs.get( i ); IType typeParam = null; if( !bKeepTypeVars && typeArg.isTypeVariable() ) { if( !recursiveTypes.contains( typeArg ) ) { IType t = getActualType( typeArg, actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( !(t instanceof ErrorType) ) { typeParam = t; } } if( typeParam == null ) { List<AsmType> typeParameters = typeArg.getTypeParameters(); if( typeParameters.isEmpty() ) { typeParam = JavaTypes.OBJECT(); } else { AsmType bound = typeParameters.get( 0 ); if( !recursiveTypes.contains( bound ) ) { typeParam = getActualType( bound, actualParamByVarName, bKeepTypeVars, recursiveTypes ); } else if( bound.isParameterized() ) { typeParam = getActualType( bound.getRawType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ); } else { throw new IllegalStateException( "Expecting bound to be a parameterized here" ); } } } } else { if( typeArg instanceof AsmWildcardType && (((AsmWildcardType)typeArg).getBound() == null || !((AsmWildcardType)typeArg).isCovariant() ) ) { // Get the bounding type from the corresponding type var IJavaClassInfo classInfo = TypeSystem.getDefaultTypeLoader().getJavaClassInfo( type.getRawType().getName() ); if( classInfo != null && !isContravariantWildcardOnFunctionalInterface( (AsmWildcardType)typeArg, classInfo.getName() ) ) { List<AsmType> boundingTypes = ((AsmTypeJavaClassType)classInfo.getTypeParameters()[i]).getType().getTypeParameters(); AsmType boundingType = boundingTypes.isEmpty() ? null : boundingTypes.get( 0 ); if( boundingType != null ) { typeArg = boundingType; } } } typeParam = getActualType( typeArg, actualParamByVarName, bKeepTypeVars, recursiveTypes ); } types.add( typeParam ); } String rawTypeName = type.getRawType().getName(); IType genType = TypeSystem.getByFullNameIfValid( rawTypeName );//getActualType( type.getRawType(), actualParamByVarName, bKeepTypeVars, recursiveTypes ); if( genType == null ) { return ErrorType.getInstance( rawTypeName ); //throw new TypeNotPresentException( rawTypeName, null ); } return genType.getParameterizedType( types.toArray( new IType[types.size()] ) ); } finally { recursiveTypes.remove( type ); } } } throw new IllegalStateException(); //return parseType( type.getFqn(), actualParamByVarName, bKeepTypeVars, null ); } private static boolean isContravariantWildcardOnFunctionalInterface( AsmWildcardType typeArg, String fqn ) { IType genType = TypeSystem.getByFullNameIfValid( fqn ); return !typeArg.isCovariant() && genType instanceof IJavaType && FunctionToInterfaceCoercer.getSingleMethodFromJavaInterface( (IJavaType)genType ) != null; } public static IType getActualType( IType type, TypeVarToTypeMap actualParamByVarName ) { return getActualType( type, actualParamByVarName, false ); } public static IType getActualType( IType type, TypeVarToTypeMap actualParamByVarName, boolean bKeepTypeVars ) { return getActualType( type, actualParamByVarName, bKeepTypeVars, new HashSet<IType>() ); } public static IType getActualType( IType type, TypeVarToTypeMap actualParamByVarName, boolean bKeepTypeVars, Set<IType> visited ) { int iArrayDims = 0; if( type != null && type.isArray() ) { for( iArrayDims = 0; type.isArray(); iArrayDims++ ) { type = type.getComponentType(); } } if( visited.contains( type ) ) { return type; } visited.add( type ); if( type instanceof TypeVariableType ) { TypeVariableType saveType = (TypeVariableType)type; type = actualParamByVarName.get( (ITypeVariableType)type ); if( type == null ) { if( bKeepTypeVars ) { type = saveType; } } else { if( bKeepTypeVars && type.equals( saveType ) && ((ITypeVariableType)type).getBoundingType() != null ) { IType boundingType = ((ITypeVariableType)type).getBoundingType(); IType actualBoundingType = getActualType( boundingType, actualParamByVarName, bKeepTypeVars, visited ); visited.remove( boundingType ); if( actualBoundingType != boundingType ) { TypeVariableDefinitionImpl tvd = ((TypeVariableDefinitionImpl)((ITypeVariableType)type).getTypeVarDef()).clone( actualBoundingType ); type = new TypeVariableType( tvd, ((ITypeVariableType)type).getTypeVarDef().getEnclosingType() instanceof IFunctionType ); } } else if( !bKeepTypeVars && !isParameterizedWith( type, saveType ) ) { type = getActualType( type, actualParamByVarName, bKeepTypeVars, visited ); visited.remove( type ); } else if( !bKeepTypeVars ) { type = getDefaultParameterizedTypeWithTypeVars( type ); } } } else if( type instanceof FunctionType ) { if( !(type instanceof ErrorTypeInfo.UniversalFunctionType) ) { type = ((FunctionType)type).parameterize( (FunctionType)type, actualParamByVarName, bKeepTypeVars ); } } else if( type != null && type.isParameterizedType() ) { IType[] typeParams = type.getTypeParameters(); IType[] actualParamTypes = new IType[typeParams.length]; boolean bDifferent = false; for( int i = 0; i < typeParams.length; i++ ) { boolean bAlreadyVisiting = visited.contains( typeParams[i] ); IType actualType = getActualType( typeParams[i], actualParamByVarName, bKeepTypeVars, visited ); if( !bAlreadyVisiting ) { visited.remove( typeParams[i] ); } if( actualType == null ) { actualType = JavaTypes.OBJECT(); } actualParamTypes[i] = actualType; if( actualType != typeParams[i] ) { bDifferent = true; } } visited.remove( type ); type = bDifferent ? TypeLord.getPureGenericType( type ).getParameterizedType( actualParamTypes ) : type; } if( iArrayDims > 0 && type != null ) { for( int j = 0; j < iArrayDims; j++ ) { type = type.getArrayType(); } } return type; } public static boolean isParameterizedWith( IType type, TypeVariableType typeVar ) { type = getCoreType( type ); if( type.equals( typeVar ) ) { return true; } if( type instanceof FunctionType ) { IFunctionType funType = (IFunctionType)type; IType[] types = funType.getParameterTypes(); for( IType param : types ) { if( isParameterizedWith( param, typeVar ) ) { return true; } } return isParameterizedWith( funType.getReturnType(), typeVar ); } else if( type.isParameterizedType() ) { for( IType typeParam : type.getTypeParameters() ) { if( isParameterizedWith( typeParam, typeVar ) ) { return true; } } } return false; } public static IType parseType( String strParameterizedTypeName, TypeVarToTypeMap actualParamByVarName ) { return parseType( strParameterizedTypeName, actualParamByVarName, null ); } public static IType parseType( String strParameterizedTypeName, TypeVarToTypeMap actualParamByVarName, ITypeUsesMap typeUsesMap ) { try { ITypeLiteralExpression expression = parseTypeLiteral( strParameterizedTypeName, actualParamByVarName, typeUsesMap ); return expression.getType().getType(); } catch( ParseResultsException e ) { throw new RuntimeException( "Unable to parse the type " + strParameterizedTypeName + ". When attempting to parse this " + "as a type literal, a parse error occured.", e ); } } public static ITypeLiteralExpression parseTypeLiteral( String strParameterizedTypeName, TypeVarToTypeMap actualParamByVarName, ITypeUsesMap typeUsesMap ) throws ParseResultsException { StringTokenizer tokenizer = new StringTokenizer( strParameterizedTypeName, " <>[]?:(),", true ); StringBuilder sbType = new StringBuilder(); while( tokenizer.hasMoreTokens() ) { String strToken = tokenizer.nextToken(); IType type = actualParamByVarName.getByString( strToken ); String resolvedTypeName; if( type != null ) { if( type.isParameterizedType() ) { type = resolveParameterizedType( type, actualParamByVarName ); } if( type instanceof TypeVariableType ) { type = ((TypeVariableType)type).getBoundingType(); } resolvedTypeName = type instanceof TypeVariableType ? type.getRelativeName() : type.getName(); } else { resolvedTypeName = strToken; } boolean bFirstToken = sbType.length() == 0; if( bFirstToken ) { if( "?".equals( resolvedTypeName ) ) { resolvedTypeName = JavaTypes.OBJECT().getName(); } } sbType.append( resolvedTypeName ); } String strNormalizedType = sbType.toString().replace( "$", "." ); GosuParser parser = (GosuParser)GosuParserFactory.createParser( strNormalizedType, new StandardSymbolTable(), ScriptabilityModifiers.SCRIPTABLE ); parser.setAllowWildcards( true ); if( typeUsesMap != null ) { parser.setTypeUsesMap(typeUsesMap); } parser.pushIgnoreTypeDeprecation(); try { return parser.parseTypeLiteral( (IScriptPartId)null ); } finally { parser.popIgnoreTypeDeprecation(); } } private static IType resolveParameterizedType( IType parameterizedType, TypeVarToTypeMap actualParamByVarName ) { List<IType> resolvedParams = new ArrayList<IType>(); for( IType paramType : parameterizedType.getTypeParameters() ) { if( paramType instanceof TypeVariableType && actualParamByVarName.containsKey( (ITypeVariableType)paramType ) ) { resolvedParams.add( actualParamByVarName.get( (ITypeVariableType)paramType ) ); } else { if( paramType.isParameterizedType() ) { resolvedParams.add( resolveParameterizedType( paramType, actualParamByVarName ) ); } else { resolvedParams.add( paramType ); } } } return parameterizedType.getGenericType().getParameterizedType( resolvedParams.toArray( new IType[resolvedParams.size()] ) ); } public static TypeVarToTypeMap mapTypeByVarName( IType ownersType, IType declaringType ) { TypeVarToTypeMap actualParamByVarName; ownersType = findActualDeclaringType( ownersType, declaringType ); if( ownersType != null && ownersType.isParameterizedType() ) { actualParamByVarName = mapActualTypeByVarName( ownersType ); } else { actualParamByVarName = mapGenericTypeByVarName( ownersType ); if( ownersType != null ) { while( ownersType.getEnclosingType() != null ) { ownersType = ownersType.getEnclosingType(); TypeVarToTypeMap vars = mapGenericTypeByVarName( ownersType ); if( actualParamByVarName.isEmpty() ) { actualParamByVarName = vars; } else { actualParamByVarName.putAll( vars ); } } } } return actualParamByVarName; } public static IType makeParameteredType( IType genType, TypeVarToTypeMap inferenceMap ) { IGenericTypeVariable[] gtvs = getPureGenericType( genType ).getGenericTypeVariables(); IType[] typeParams = new IType[gtvs.length]; int i = 0; for( IGenericTypeVariable gtv: gtvs ) { typeParams[i] = inferenceMap.get( gtv.getTypeVariableDefinition().getType() ); if( typeParams[i] == null ) { if( genType.isParameterizedType() ) { typeParams[i] = genType.getTypeParameters()[i]; } else { return null; } } i++; } return genType.getParameterizedType( typeParams ); } // If the declaring type is generic and the owning type is parameterized, we need to // find the corresponding parameterized type of the declaring type e.g. // class Base<T> { // function blah() : Bar<T> {} // class Foo<T> extends Base<T> {} // new Foo<String>().blah() // infer return type as Bar<String> // The declaring class of blah() is generic class Base<T> (not a parameterized one), // while the owner's type is Foo<String>, thus in order to resolve the actual return // type for blah() we must walk the ancestry of Foo<String> until find the corresponding // parameterized type for Base<T>. private static IType findActualDeclaringType( IType ownersType, IType declaringType ) { if( ownersType == null ) { return null; } if( declaringType.isParameterizedType() && !declaringType.isGenericType() ) { return declaringType; } if( ownersType == declaringType ) { return declaringType; } if( ownersType.getGenericType() == declaringType ) { return ownersType; } IType actualDeclaringType = findActualDeclaringType( ownersType.getSupertype(), declaringType ); if( actualDeclaringType != null && actualDeclaringType != declaringType ) { return actualDeclaringType; } for( IType iface : ownersType.getInterfaces() ) { actualDeclaringType = findActualDeclaringType( iface, declaringType ); if( actualDeclaringType != null && actualDeclaringType != declaringType ) { return actualDeclaringType; } } return declaringType; } private static TypeVarToTypeMap mapActualTypeByVarName( IType ownersType ) { TypeVarToTypeMap actualParamByVarName = new TypeVarToTypeMap(); IGenericTypeVariable[] vars = ownersType.getGenericType().getGenericTypeVariables(); if (vars != null) { IType[] paramArgs = ownersType.getTypeParameters(); for( int i = 0; i < vars.length; i++ ) { IGenericTypeVariable typeVar = vars[i]; if( paramArgs.length > i ) { actualParamByVarName.put( typeVar.getTypeVariableDefinition().getType(), paramArgs[i] ); } } } return actualParamByVarName; } private static TypeVarToTypeMap mapGenericTypeByVarName( IType ownersType ) { TypeVarToTypeMap genericParamByVarName = TypeVarToTypeMap.EMPTY_MAP; IType genType = null; if( ownersType != null ) { genType = ownersType.getGenericType(); } if( genType != null ) { genericParamByVarName = new TypeVarToTypeMap(); IGenericTypeVariable[] vars = genType.getGenericTypeVariables(); if( vars != null ) { for( int i = 0; i < vars.length; i++ ) { IGenericTypeVariable typeVar = vars[i]; ITypeVariableType type = typeVar.getTypeVariableDefinition().getType(); if( !genericParamByVarName.containsKey( type ) ) { genericParamByVarName.put( type, new TypeVariableType( ownersType, typeVar ) ); } } } } return genericParamByVarName; } public static String getNameWithQualifiedTypeVariables( IType type, boolean includeModules ) { if( type.isArray() ) { return getNameWithQualifiedTypeVariables( type.getComponentType(), includeModules ) + "[]"; } else if( type.isParameterizedType() ) { String strParams = getNameOfParams( type.getTypeParameters(), false, true, includeModules ); return getPureGenericType( type ).getName() + strParams; } else if( type instanceof TypeVariableType ) { if( type.getEnclosingType() != null ) { return ((TypeVariableType)type).getNameWithEnclosingType(); } } return type.getName(); } public static String getNameWithBoundQualifiedTypeVariables( IType type, boolean includeModules ) { if( type.isArray() ) { return getNameWithQualifiedTypeVariables( type.getComponentType(), includeModules ) + "[]"; } else if( type.isParameterizedType() ) { String strParams = getNameOfParams( type.getTypeParameters(), false, true, includeModules ); return getPureGenericType( type ).getName() + strParams; } else if( type instanceof TypeVariableType ) { if( type.getEnclosingType() != null ) { return ((TypeVariableType)type).getNameWithBoundingType(); } } return type.getName(); } public static String getNameOfParams( IType[] paramTypes, boolean bRelative, boolean bWithEnclosingType ) { return getNameOfParams( paramTypes, bRelative, bWithEnclosingType, false ); } public static String getNameOfParams( IType[] paramTypes, boolean bRelative, boolean bWithEnclosingType, boolean bIncludeModule ) { return _getNameOfParams( paramTypes, bRelative, bWithEnclosingType, bIncludeModule, new HashSet<>() ); } private static String _getNameOfParams( IType[] paramTypes, boolean bRelative, boolean bWithEnclosingType, boolean bIncludeModule, Set<IType> visited ) { StringBuilder sb = new StringBuilder( "<" ); for( int i = 0; i < paramTypes.length; i++ ) { IType paramType = paramTypes[i]; if( bRelative ) { sb.append( paramType.getRelativeName() ); } else { appendTypeName( bWithEnclosingType, bIncludeModule, sb, paramType, visited ); } if( i < paramTypes.length - 1 ) { sb.append( ", " ); } } sb.append( '>' ); return sb.toString(); } private static StringBuilder appendTypeName( boolean bWithEnclosingType, boolean bIncludeModule, StringBuilder sb, IType paramType, Set<IType> visited ) { if( paramType.isArray() ) { appendTypeName( bWithEnclosingType, bIncludeModule, sb, paramType.getComponentType(), visited ).append( "[]" ); } else if( bWithEnclosingType && paramType instanceof TypeVariableType && !visited.contains( paramType ) ) { visited.add( paramType ); try { TypeVariableType type = (TypeVariableType)paramType; if( type.getEnclosingType() != null ) { if( bIncludeModule && !(type.getEnclosingType() instanceof INonLoadableType) ) { sb.append( type.getEnclosingType().getTypeLoader().getModule().getName() ).append( "." ); } sb.append( type.getNameWithEnclosingType() ); ITypeVariableDefinition typeVarDef = type.getTypeVarDef(); if( typeVarDef != null ) { sb.append( typeVarDef.getVariance().getSymbol() ); IType boundingType = typeVarDef.getBoundingType(); if( type.isFunctionStatement() && boundingType != null && boundingType != JavaTypes.OBJECT() ) { sb.append( '-' ); appendTypeName( bWithEnclosingType, bIncludeModule, sb, boundingType, visited ); } } } else { sb.append( type.getName() ); } } finally { visited.remove( paramType ); } } else if( bWithEnclosingType && paramType.isParameterizedType() ) { sb.append( paramType.getGenericType().getName() ); sb.append( _getNameOfParams( paramType.getTypeParameters(), false, bWithEnclosingType, bIncludeModule, visited ) ); } else { if( bIncludeModule && !(paramType instanceof INonLoadableType) ) { ITypeLoader typeLoader = paramType.getTypeLoader(); if( typeLoader != null ) { IModule oldModule = typeLoader.getModule(); if( oldModule != null ) { sb.append( oldModule.getName() ).append( "." ); } } } sb.append( paramType.getName() ); } return sb; } public static boolean isDelegatableInterface( IType declaringType, IType iface ) { if( iface.isAssignableFrom( declaringType ) ) { return true; } IType superClass = declaringType.getSupertype(); if( superClass != null && isDelegatableInterface( superClass, iface ) ) { return true; } IType[] interfaces = declaringType.getInterfaces(); if( interfaces != null ) { for( IType t : interfaces ) { if( isDelegatableInterface( t, iface ) ) { return true; } } } return false; } public static IType findParameterizedStructureType( IType structureType, IType from ) { TypeVarToTypeMap inferenceMap = new TypeVarToTypeMap(); if( !StandardCoercionManager.isStructurallyAssignable_Laxed( structureType, from, inferenceMap ) ) { return null; } return TypeLord.makeParameteredType( structureType, inferenceMap ); } /** * Finds a parameterized type in the ancestry of a given type. For instance, * given the type for ArrayList&lt;Person&gt; as the sourceType and List as * the rawGenericType, returns List&lt;Person&gt;. * * @param sourceType The type to search in. * @param rawGenericType The raw generic type of the parameterized type to * search for e.g., List is the raw generic type of List&lt;String&gt;. * * @return A parameterization of rawGenericType corresponding with the type * params of sourceType. */ // List<Foo> ArrayList<Foo> List public static IType findParameterizedType( IType sourceType, IType rawGenericType ) { return findParameterizedType( sourceType, rawGenericType, false ); } public static IType findParameterizedType( IType sourceType, IType rawGenericType, boolean bForAssignability ) { if( sourceType == null ) { return null; } rawGenericType = getPureGenericType( rawGenericType ); final IType srcRawType = sourceType.getGenericType(); if( srcRawType == rawGenericType || !bForAssignability && srcRawType instanceof IMetaType && rawGenericType == JavaTypes.CLASS() ) { return sourceType; } IType parameterizedType = findParameterizedType( sourceType.getSupertype(), rawGenericType, bForAssignability ); if( parameterizedType != null ) { return parameterizedType; } IType[] interfaces = sourceType.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { IType iface = interfaces[i]; parameterizedType = findParameterizedType( iface, rawGenericType, bForAssignability ); if( parameterizedType != null ) { return parameterizedType; } } return null; } // ArrayList<Foo> List<Foo> ArrayList<Z> public static IType findParameterizedType_Reverse( IType sourceType, IType targetType ) { if( sourceType == null || targetType == null ) { return null; } if( !sourceType.isParameterizedType() ) { return null; } // List<Z> IType sourceTypeInHier = findParameterizedType( targetType, getPureGenericType( sourceType ) ); if( sourceTypeInHier == null || !sourceTypeInHier.isParameterizedType() ) { return null; } TypeVarToTypeMap map = new TypeVarToTypeMap(); IType[] params = sourceTypeInHier.getTypeParameters(); for( int iPos = 0; iPos < params.length; iPos++ ) { if( params[iPos] instanceof ITypeVariableType ) { map.put( (ITypeVariableType)params[iPos], sourceType.getTypeParameters()[iPos] ); } } // ArrayList<Foo> return getActualType( targetType, map, true ); } // Todo: the above method is nearly identical to this one. lets see about combining them public static IType findParameterizedTypeInHierarchy( IType sourceType, IType rawGenericType ) { if( sourceType == null ) { return null; } if( sourceType.isParameterizedType() && sourceType.getGenericType().equals( rawGenericType ) ) { return sourceType; } IType[] list = sourceType.getInterfaces(); for( int i = 0; i < list.length; i++ ) { IType returnType = findParameterizedTypeInHierarchy( list[i], rawGenericType ); if( returnType != null ) { return returnType; } } return findParameterizedTypeInHierarchy( sourceType.getSupertype(), rawGenericType ); } public static void addAllClassesInClassHierarchy( Class entityClass, Set<Class> set ) { if( !set.add( entityClass ) ) { return; } Class[] interfaces = entityClass.getInterfaces(); for( int i = 0; i < interfaces.length; i++ ) { addAllClassesInClassHierarchy( interfaces[i], set ); } if( entityClass.getSuperclass() != null ) { addAllClassesInClassHierarchy( entityClass.getSuperclass(), set ); } } private static void addAllClassesInClassHierarchy( IJavaClassInfo entityClass, Set<IJavaClassInfo> set ) { if( !set.add( entityClass ) ) { return; } IJavaClassInfo[] interfaces = entityClass.getInterfaces(); for( int i = 0; i < interfaces.length; i++ ) { addAllClassesInClassHierarchy( interfaces[i], set ); } if( entityClass.getSuperclass() != null ) { addAllClassesInClassHierarchy( entityClass.getSuperclass(), set ); } } public static void addAllClassesInClassHierarchy( IType type, Set<IType> set ) { addAllClassesInClassHierarchy( type, set, false ); } public static void addAllClassesInClassHierarchy( IType type, Set<IType> set, boolean bForce ) { if( !set.add( type ) && !bForce ) { return; } boolean bFromStructure = type instanceof IGosuClass && ((IGosuClass)type).isStructure(); for( IType iface : type.getInterfaces() ) { if( !bFromStructure || !(iface instanceof IGosuClass) || ((IGosuClass)iface).isStructure() ) { addAllClassesInClassHierarchy( iface, set ); } } if( type.getSupertype() != null ) { addAllClassesInClassHierarchy( type.getSupertype(), set ); } if( type.isParameterizedType() ) { set.add( type.getGenericType() ); } } public static <E extends IType> E getPureGenericType( E type ) { if ( type == null || TypeSystem.isDeleted(type)) { return null; } if( type.isArray() ) { return (E)getPureGenericType( type.getComponentType() ).getArrayType(); } //## todo: write a test to verify whether or not this is correct // if( type instanceof CompoundType ) { // Set<IType> types = ((CompoundType)type).getTypes(); // IType[] genTypes = new IType[types.size()]; // int i = 0; // for( IType comp: types ) { // genTypes[i++] = getPureGenericType( comp ); // return (E)CompoundType.get( genTypes ); while( type.isParameterizedType() ) { //noinspection unchecked type = (E)type.getGenericType(); } return type; } public static IType deriveParameterizedTypeFromContext( IType type, IType contextType ) { if( !type.isGenericType() || type.isParameterizedType() ) { return type; } if( type instanceof MetaType ) { return MetaType.DEFAULT_TYPE_TYPE.get(); } if( contextType == null || !contextType.isParameterizedType() ) { return makeDefaultParameterizedType( type ); } IType genType = TypeLord.getPureGenericType( contextType ); if( !genType.isGenericType() || !genType.isAssignableFrom( type ) ) { return makeDefaultParameterizedType( type ); } IType parameterizedWithTypeVars = type.getParameterizedType( Arrays.stream( type.getGenericTypeVariables() ).map( gtv -> gtv.getTypeVariableDefinition().getType() ).toArray( IType[]::new ) ); IType result = findParameterizedType_Reverse( contextType, parameterizedWithTypeVars ); if( result == null ) { result = makeDefaultParameterizedType( type ); } return result; } public static IType makeDefaultParameterizedType( IType type ) { if( type != null && !(type instanceof IGosuEnhancementInternal) && !type.isParameterizedType() && type.isGenericType() ) { if( type instanceof MetaType ) { return MetaType.DEFAULT_TYPE_TYPE.get(); } IType[] boundingTypes = new IType[type.getGenericTypeVariables().length]; for( int i = 0; i < boundingTypes.length; i++ ) { boundingTypes[i] = type.getGenericTypeVariables()[i].getBoundingType(); IGenericTypeVariable typeVar = type.getGenericTypeVariables()[i]; if( TypeLord.isRecursiveType( typeVar.getTypeVariableDefinition().getType(), typeVar.getBoundingType() ) ) { return type; } } if( boundingTypes.length == 0 ) { return type; } type = type.getParameterizedType( boundingTypes ); } return type; } public static IType replaceTypeVariableTypeParametersWithBoundingTypes( IType type ) { return replaceTypeVariableTypeParametersWithBoundingTypes( type, null ); } public static IType replaceTypeVariableTypeParametersWithBoundingTypes( IType type, IType enclType ) { if( type instanceof ITypeVariableType ) { if( isRecursiveType( (ITypeVariableType)type, ((ITypeVariableType)type).getBoundingType() ) ) { // short-circuit recursive typevar return TypeLord.getPureGenericType( ((ITypeVariableType)type).getBoundingType() ); } if( enclType != null && enclType.isParameterizedType() ) { TypeVarToTypeMap map = mapTypeByVarName( enclType, enclType ); return replaceTypeVariableTypeParametersWithBoundingTypes( getActualType( ((ITypeVariableType)type).getBoundingType(), map, true ) ); } return replaceTypeVariableTypeParametersWithBoundingTypes( ((ITypeVariableType)type).getBoundingType(), enclType ); } if( type.isArray() ) { return replaceTypeVariableTypeParametersWithBoundingTypes( type.getComponentType(), enclType ).getArrayType(); } if( type instanceof CompoundType ) { Set<IType> types = ((CompoundType)type).getTypes(); Set<IType> newTypes = new HashSet<>(); for( IType t: types ) { newTypes.add( replaceTypeVariableTypeParametersWithBoundingTypes( t ) ); } if( newTypes.size() == 1 ) { return newTypes.iterator().next(); } return CompoundType.get( newTypes ); } if( type.isParameterizedType() ) { IType[] typeParams = type.getTypeParameters(); IType[] concreteParams = new IType[typeParams.length]; for( int i = 0; i < typeParams.length; i++ ) { concreteParams[i] = replaceTypeVariableTypeParametersWithBoundingTypes( typeParams[i], enclType ); } type = type.getParameterizedType( concreteParams ); } else { if( type.isGenericType() ) { IType[] boundingTypes = new IType[type.getGenericTypeVariables().length]; for( int i = 0; i < boundingTypes.length; i++ ) { boundingTypes[i] = type.getGenericTypeVariables()[i].getBoundingType(); if( TypeLord.isRecursiveType( type.getGenericTypeVariables()[i].getTypeVariableDefinition().getType(), boundingTypes[i] ) ) { return type; } } for( int i = 0; i < boundingTypes.length; i++ ) { boundingTypes[i] = replaceTypeVariableTypeParametersWithBoundingTypes( boundingTypes[i], enclType ); } type = type.getParameterizedType( boundingTypes ); } } return type; } public static IType replaceRawGenericTypesWithDefaultParameterizedTypes( IType type ) { if( type == null ) { return null; } if( type.isArray() ) { IType compType = replaceRawGenericTypesWithDefaultParameterizedTypes( type.getComponentType() ); if( compType != type.getComponentType() ) { return compType.getArrayType(); } return type; } if( type.isParameterizedType() ) { final IType[] typeParameters = type.getTypeParameters(); IType[] typeParams = new IType[typeParameters.length]; boolean bReplaced = false; for( int i = 0; i < typeParameters.length; i++ ) { IType typeParam = typeParameters[i]; typeParams[i] = replaceRawGenericTypesWithDefaultParameterizedTypes( typeParam ); if( typeParam != typeParams[i] ) { bReplaced = true; } } return bReplaced ? type.getParameterizedType( typeParams ) : type; } if( type.isGenericType() ) { return getDefaultParameterizedType( type ); } return type; } public static IType getDefaultParameterizedType( IType type ) { if( type.isArray() ) { IType defType = getDefaultParameterizedType( type.getComponentType() ); if( defType != type ) { return defType.getArrayType(); } return type; } if( type instanceof CompoundType ) { return makeDefaultParameterizedTypeForCompoundType( type ); } if( !type.isGenericType() && !type.isParameterizedType() ) { return type; } type = getPureGenericType( type ); return makeDefaultParameterizedType( type ); } private static IType makeDefaultParameterizedTypeForCompoundType( IType type ) { IType[] defCompTypes = new IType[type.getCompoundTypeComponents().size()]; int i = 0; boolean bDifferent = false; for( IType compType: type.getCompoundTypeComponents() ) { defCompTypes[i++] = getDefaultParameterizedType( compType ); bDifferent = bDifferent || defCompTypes[i] != compType; } if( bDifferent ) { type = CompoundType.get( defCompTypes ); } return type; } public static IType getDefaultParameterizedTypeWithTypeVars( IType type ) { return getDefaultParameterizedTypeWithTypeVars(type, null, new HashSet<IType>()); } public static IType getDefaultParameterizedTypeWithTypeVars( IType type, TypeVarToTypeMap map ) { return getDefaultParameterizedTypeWithTypeVars( type, map, new HashSet<IType>() ); } public static IType getDefaultParameterizedTypeWithTypeVars( IType type, TypeVarToTypeMap map, Set<IType> visited ) { if( type.isArray() ) { return getDefaultParameterizedTypeWithTypeVars( type.getComponentType(), map, visited ).getArrayType(); } if( type instanceof ITypeVariableType ) { if( map != null ) { final IType assignedType = map.get( (ITypeVariableType)type ); if( assignedType != null ) { return assignedType; } } return getDefaultParameterizedTypeWithTypeVars(((ITypeVariableType) type).getBoundingType(), map, visited); } if( type instanceof ITypeVariableArrayType ) { return getDefaultParameterizedTypeWithTypeVars( ((ITypeVariableType)type.getComponentType()).getBoundingType(), map, visited ).getArrayType(); } if( !type.isGenericType() && !type.isParameterizedType() ) { return type; } if( !visited.contains( type ) ) { visited.add( type ); if( isParameterizedType( type ) && isRecursiveType( type ) ) { IType[] typeParameters = type.getTypeParameters(); IType[] typeParams = new IType[typeParameters.length]; int i = 0; for( IType param: typeParameters ) { typeParams[i++] = getDefaultParameterizedTypeWithTypeVars( param, map, visited ); } return getPureGenericType( type ).getParameterizedType( typeParams ); } else if( type.isGenericType() && !type.isParameterizedType() && isRecursiveTypeFromBase( type ) ) { final IGenericTypeVariable[] gvs = type.getGenericTypeVariables(); IType[] typeParams = new IType[gvs.length]; int i = 0; for( IGenericTypeVariable param: gvs ) { final ITypeVariableDefinition typeDef = param.getTypeVariableDefinition(); if( typeDef != null ) { ITypeVariableType typeVarType = typeDef.getType(); if( isRecursiveType( typeVarType, typeVarType.getBoundingType() ) ) { // short-circuit recursive typevar typeParams[i++] = TypeLord.getPureGenericType( typeVarType.getBoundingType() ); } else { typeParams[i++] = getDefaultParameterizedTypeWithTypeVars( typeVarType, map, visited ); } } else { typeParams[i++] = getDefaultParameterizedTypeWithTypeVars( typeDef.getBoundingType(), map, visited ); } } return getPureGenericType( type ).getParameterizedType( typeParams ); } } type = getPureGenericType( type ); return makeDefaultParameterizedType( type ); } public static boolean isRecursiveTypeFromBase( IType rootType ) { if( !rootType.isGenericType() && !rootType.isParameterizedType() ) { return false; } IType genType = TypeLord.getPureGenericType( rootType ); if( genType != TypeLord.getDefaultParameterizedType( genType ) ) { return false; } if( rootType.isGenericType() && !rootType.isParameterizedType() ) { if( rootType == TypeLord.getDefaultParameterizedType( rootType ) ) { return true; } } else if( rootType.isParameterizedType() ) { for( IType typeParam : rootType.getTypeParameters() ) { if( isRecursiveTypeFromBase( typeParam ) ) { return true; } } } return false; } public static boolean isRecursiveType( IType declaringClass ) { return _isRecursiveType( declaringClass, new HashSet<IType>() ); } private static boolean _isRecursiveType( IType declaringClass, Set<IType> visited ) { if( declaringClass instanceof ITypeVariableType ) { if( visited.contains( declaringClass ) ) { return true; } visited.add( declaringClass ); try { return _isRecursiveType( ((ITypeVariableType)declaringClass).getBoundingType(), visited ); } finally { visited.remove( declaringClass ); } } if( declaringClass.isArray() ) { return _isRecursiveType( declaringClass.getComponentType(), visited ); } if( !declaringClass.isGenericType() && !declaringClass.isParameterizedType() ) { return false; } if( declaringClass.isGenericType() && !declaringClass.isParameterizedType() ) { for( IGenericTypeVariable gtv: declaringClass.getGenericTypeVariables() ) { ITypeVariableDefinition tvd = gtv.getTypeVariableDefinition(); if( tvd != null ) { if( _isRecursiveType( tvd.getType(), visited ) ) { return true; } } } } else if( declaringClass.isParameterizedType() ) { for( IType typeParam : declaringClass.getTypeParameters() ) { if( _isRecursiveType( typeParam, visited ) ) { return true; } } } return false; } public static boolean isSubtype( IType subtype, IType supertype ) { if( subtype == null ) { return false; } // Make sure we're dealing with pure types before doing any checks subtype = getPureGenericType( subtype ); supertype = getPureGenericType( supertype ); if( supertype instanceof IGosuClassInternal ) { if( ((IGosuClassInternal)supertype).isSubClass( subtype ) ) { return true; } } IType st = getPureGenericType( subtype.getSupertype() ); return st == supertype || isSubtype( st, supertype ); } static String fixSunInnerClassBug( String type ) { int i = type.indexOf( "$", 0 ); if( i < 0 ) { return type; } else { int n = 0; i = 0; StringBuilder sb = new StringBuilder( type ); while( i >= 0 ) { i = findNthPositionOfString( n, sb, "$" ); removeDuplicateClassName( sb, i ); n++; } return sb.toString(); } } private static int findNthPositionOfString( int n, StringBuilder sb, String str ) { int count = 0; int i = 0; while( count <= n ) { i = sb.indexOf( str, i + 1 ); count++; } return i; } static void removeDuplicateClassName( StringBuilder sb, int dollarSignPosition ) { StringBuilder foundBuffer = new StringBuilder(); boolean chopped = false; int start = dollarSignPosition - 1; while( start >= 0 ) { foundBuffer.append( sb.charAt( start ) ); if( repeatsWithDot( foundBuffer ) && !chopped ) { foundBuffer.setLength( foundBuffer.length() / 2 ); chopped = true; break; } start } if( chopped ) { sb.replace( start, dollarSignPosition, foundBuffer.reverse().toString() ); } } static boolean repeatsWithDot( StringBuilder sb ) { if( sb == null || sb.length() % 2 == 0 ) { return false; } int halfPoint = sb.length() / 2; if( sb.charAt( halfPoint ) != '.' ) { return false; } for( int i = 0; i < halfPoint; i++ ) { if( sb.charAt( i ) != sb.charAt( i + halfPoint + 1 ) ) { return false; } } return true; } public static boolean areGenericOrParameterizedTypesAssignable( IType to, IType from ) { return ASSIGNABILITY_CACHE.get(Pair.make(to, from)); } private static boolean areGenericOrParameterizedTypesAssignableInternal( IType to, IType from ) { if( from instanceof CompoundType ) { Set<IType> types = ((CompoundType)from).getTypes(); for( IType type : types ) { if( areGenericOrParameterizedTypesAssignable( to, type ) ) { return true; } } return false; } else if( to.isParameterizedType() || to.isGenericType() ) { if( from.isGenericType() && !from.isParameterizedType() && to.isParameterizedType() && TypeLord.getPureGenericType( to ).isAssignableFrom( from ) ) { // Raw generic type is assignable to any parameterized version of it return true; } IType relatedParameterizedType = findParameterizedType( from, to.getGenericType(), true ); if( relatedParameterizedType == null ) { if( from == to.getGenericType() ) { // Handle case List<Object> assignable from List relatedParameterizedType = from; } else { return from instanceof TypeVariableType && ((TypeVariableType)from).getBoundingType() == GosuParser.PENDING_BOUNDING_TYPE; } } if( from.isGenericType() && to.isParameterizedType() && sameAsDefaultProxiedType( to, from ) ) { return true; } IType[] typeParams = to.getTypeParameters(); if( typeParams != null ) { IType[] paramTypesFrom = relatedParameterizedType.getTypeParameters(); for( int i = 0; i < typeParams.length; i++ ) { IType paramType = typeParams[i]; //## Leaving this commented out instead of deleting it to prevent it from coming back. // if( paramType instanceof TypeVariableType ) // paramType = ((TypeVariableType)paramType).getTypeVarDef().getTypeVar().getBoundingTypes()[0]; Boolean bDeclarationSiteResult = compareWithDeclarationSiteVariance( to, relatedParameterizedType, i ); if( bDeclarationSiteResult != null ) { if( !bDeclarationSiteResult ) { return false; } continue; } if( paramType != JavaTypes.OBJECT() && (paramTypesFrom == null || paramTypesFrom.length <= i || (!paramType.isAssignableFrom( paramTypesFrom[i] ) && !StandardCoercionManager.isStructurallyAssignable( paramType, paramTypesFrom[i] ) && !(JavaTypes.CLASS().isAssignableFrom( to ) && StandardCoercionManager.isStructurallyAssignable( paramType, MetaType.getLiteral( paramTypesFrom[i] ) )))) ) { return false; } } } return true; } return false; } private static Boolean compareWithDeclarationSiteVariance( IType to, IType from, int iIndex ) { IType toGenType = getPureGenericType( to ); IType fromGenType = getPureGenericType( from ); if( toGenType != fromGenType ) { return null; } IGenericTypeVariable[] toGtvs = toGenType.getGenericTypeVariables(); if( toGtvs == null || iIndex >= toGtvs.length ) { return null; } IGenericTypeVariable[] fromGtvs = fromGenType.getGenericTypeVariables(); if( fromGtvs == null || iIndex >= fromGtvs.length ) { return null; } if( toGtvs.length != fromGtvs.length ) { return null; } IType[] toTypeParams = to.getTypeParameters(); if( toTypeParams == null || iIndex >= toTypeParams.length ) { return null; } IType[] fromTypeParams = from.getTypeParameters(); if( fromTypeParams == null || iIndex >= fromTypeParams.length ) { return null; } ITypeVariableDefinition typeVarDef = toGtvs[iIndex].getTypeVariableDefinition(); if( typeVarDef == null ) { return null; } IType toTypeParam = toTypeParams[iIndex]; IType fromTypeParam = fromTypeParams[iIndex]; switch( typeVarDef.getVariance() ) { case COVARIANT: return toTypeParam.isAssignableFrom( fromTypeParam ); case CONTRAVARIANT: return fromTypeParam.isAssignableFrom( toTypeParam ); case INVARIANT: return toTypeParam.equals( fromTypeParam ); } return null; } private static boolean sameAsDefaultProxiedType( IType to, IType from ) { if( to instanceof IJavaTypeInternal && from instanceof IGosuClassInternal && ((IGosuClassInternal)from).isProxy() ) { IJavaType proxiedType = ((IGosuClassInternal)from).getJavaType(); return proxiedType != null && (TypeLord.makeDefaultParameterizedType( proxiedType ) == to || TypeLord.replaceTypeVariableTypeParametersWithBoundingTypes( proxiedType ) == to); } return false; } public static Set<String> getNamespacesFromTypeNames( Set<? extends CharSequence> typeNames, Set<String> namespaces ) { for( CharSequence typeName : typeNames ) { String strName = typeName.toString(); int iIndex = strName.lastIndexOf( '.' ); if( iIndex > 0 ) { String strPossibleEnclosingTypeName = strName.substring( 0, iIndex ); if( typeNames.contains( strPossibleEnclosingTypeName ) ) { // Don't add the enclosing type of an inner class as a namespace continue; } } addNamespace( namespaces, strName ); } namespaces.add( Gosu.NOPACKAGE ); return namespaces; } public static void addNamespace( Set<String> namespaces, String strType ) { int iIndex = strType.lastIndexOf( '.' ); if( iIndex > 0 ) { String strPackage = strType.substring( 0, iIndex ); if( namespaces.add( strPackage ) ) { // Add parent namespaces i.e. a namespace may not have a class // e.g. the java namespace has no direct classes, so we have to // add it here. addNamespace( namespaces, strPackage ); } } } public static IType getRootType(IType type) { IType result = type; while (result.getSupertype() != null || result.getSupertype() != JavaTypes.OBJECT()) { result = result.getSupertype(); } return result; } public static IType findGreatestLowerBound( IType t1, IType t2 ) { if( t1.equals( t2 ) ) { return t1; } if( t1.isAssignableFrom( t2 ) ) { return t2; } if( t2.isAssignableFrom( t1 ) ) { return t1; } return t1; //## todo: return JavaTypes.VOID() or return null or Object? } public static IType findLeastUpperBound( List<? extends IType> types ) { return findLeastUpperBoundImpl( types, new HashSet<IType>() ); } private static IType findLeastUpperBoundImpl( List<? extends IType> types, Set<IType> resolvingTypes ) { // Optimization 1: if there are no types, return void if( types.size() == 0 ) { return JavaTypes.pVOID(); } // Optimization 2: if there is one type, return that type if( types.size() == 1 ) { return types.get( 0 ); } for( IType type: types ) { if( type instanceof IPlaceholder && ((IPlaceholder)type).isPlaceholder() ) { // Dynamic type trumps all return type.getName().equals( IDynamicType.QNAME ) ? type : IDynamicType.instance(); } } IType lubType = null; boolean disJointTypes = false; boolean foundOnlyNullTypes = true; for( Iterator<? extends IType> it = types.iterator(); it.hasNext(); ) { IType type = it.next(); //nuke null types, which don't contribute to the type if( type.equals( GosuParserTypes.NULL_TYPE() ) ) { continue; } foundOnlyNullTypes = false; if( lubType == null ) { lubType = type; } if( !lubType.equals( type ) && !BeanAccess.isBoxedTypeFor( lubType, type ) && !BeanAccess.isBoxedTypeFor( type, lubType ) ) { disJointTypes = true; break; } } if( foundOnlyNullTypes ) { return GosuParserTypes.NULL_TYPE(); } if( !disJointTypes ) { return lubType; } // Short circuit recursive LUBs for( IType iType : types ) { if( resolvingTypes.contains( iType ) ) { return JavaTypes.OBJECT(); } } resolvingTypes.addAll( types ); // OK, we have disjoint types, so we need to do the full-monty LUB analysis IType seedType = types.get( 0 ); Set<IType> lubSet; if( areAllTypesBlocks( types ) ) { lubSet = findLubForBlockTypes( (List<IBlockType>)types, resolvingTypes ); } else { lubSet = new HashSet<IType>( seedType.getAllTypesInHierarchy() ); for( int i = 1; i < types.size(); i++ ) { IType iIntrinsicType = types.get( i ); lubSet.retainAll( iIntrinsicType.getAllTypesInHierarchy() ); } } pruneNonLUBs( lubSet ); if( lubSet.size() == 0 ) { /* If there is no common types, return Object */ return JavaTypes.OBJECT(); } lubSet = findParameterizationLUBS( types, lubSet, resolvingTypes ); if( lubSet.size() == 1 ) { /* If there is a single, unabiguous LUB type, return that */ return lubSet.iterator().next(); } else { return CompoundType.get( lubSet ); } } private static Set<IType> findLubForBlockTypes( List<? extends IBlockType> types, Set<IType> resolvingTypes ) { IBlockType lowerBound = types.get( 0 ); for( int i = 1; i < types.size(); i++ ) { IBlockType csr = types.get( i ); if( lowerBound.isAssignableFrom( csr ) ) { continue; } IType[] contraTypes = FunctionType.findContravariantParams( lowerBound.getParameterTypes(), csr.getParameterTypes() ); if( contraTypes == null ) { return Collections.singleton( JavaTypes.IBLOCK() ); } IType returnType = findLeastUpperBoundImpl( Arrays.asList( lowerBound.getReturnType(), csr.getReturnType() ), resolvingTypes ); lowerBound = new BlockType( returnType, contraTypes, Arrays.asList( lowerBound.getParameterNames() ), Collections.<IExpression>emptyList() ); } return Collections.singleton( lowerBound ); } private static boolean areAllTypesBlocks( List<? extends IType> types ) { for( IType t: types ) { if( !(t instanceof IBlockType) ) { return false; } } return true; } public static IType getLeastUpperBoundForPrimitiveTypes(IType t0, IType t1) { if( t0 == null || t1 == null ) { return null; } if( t0 == t1 ) { return t0; } boolean toT0FromT1 = isAWideningConversion(t0, t1); boolean toT1FromT0 = isAWideningConversion(t1, t0); if( toT0FromT1 ) { return t0; } else if( toT1FromT0 ){ return t1; } return null; } private static int getIndex(IType type) { if( type == JavaTypes.pBOOLEAN() || type == JavaTypes.BOOLEAN() ) { return 0; } else if( type == JavaTypes.pCHAR() || type == JavaTypes.CHARACTER() ) { return 1; } else if( type == JavaTypes.pBYTE() || type == JavaTypes.BYTE() ) { return 2; } else if( type == JavaTypes.pSHORT() || type == JavaTypes.SHORT() ) { return 3; } else if( type == JavaTypes.pINT() || type == JavaTypes.INTEGER() ) { return 4; } else if( type == JavaTypes.pLONG() || type == JavaTypes.LONG() ) { return 5; } else if( type == JavaTypes.pFLOAT() || type == JavaTypes.FLOAT() ) { return 6; } else if( type == JavaTypes.pDOUBLE() || type == JavaTypes.DOUBLE() ) { return 7; } else if( type == JavaTypes.BIG_INTEGER() ) { return 8; } else if( type == JavaTypes.BIG_DECIMAL() ) { return 9; } return -1; } private static boolean isAWideningConversion(IType to, IType from) { boolean[][] tab = { //FROM boolean char byte short int long float double BI BD /*boolean */ {true, false, false, false, false, false, false, false, false, false}, /*char */ {false, true, false, false, true, true, true, true, true, true }, /*byte */ {false, false, true, true, true, true, true, true, true, true }, /*short */ {false, false, false, true, true, true, true, true, true, true }, /*int */ {false, false, false, false, true, true, false, true, true, true }, /*long */ {false, false, false, false, false, true, false, false, true, true }, /*float */ {false, false, false, false, false, false, true, true, false, true }, /*double */ {false, false, false, false, false, false, false, true, false, true }, /*BigInteger */ {false, false, false, false, false, false, false, false, true, true }, /*BigDecimal */ {false, false, false, false, false, false, false, false, false, true } }; final int i = getIndex(from); final int j = getIndex(to); if(i == -1 || j == -1 ) { return false; } return tab[i][j]; } private static Set<IType> findParameterizationLUBS( List<? extends IType> currentTypes, Set<IType> lubSet, Set<IType> resolvingTypes ) { Set<IType> returnSet = new HashSet<IType>(); for( IType lub : lubSet ) { if( lub.isGenericType() && !lub.isParameterizedType() && currentTypes.size() > 1 ) { ArrayList<List<IType>> typeParametersByPosition = new ArrayList<List<IType>>( lub.getGenericTypeVariables().length ); for( int i = 0; i < lub.getGenericTypeVariables().length; i++ ) { typeParametersByPosition.add( new ArrayList<IType>() ); } for( IType initialType : currentTypes ) { IType parameterizedType = findParameterizedType( initialType, lub ); if (parameterizedType == null) { System.out.println("*** ERROR: parameteredType is null"); System.out.println("*** initialType is " + initialType); System.out.println("*** lub is " + lub); for (IType t : currentTypes) { System.out.println("*** currentTypes contains " + t); } for (IType t : lubSet) { System.out.println("*** lubSet contains " + t); } } if( !parameterizedType.isParameterizedType() ) { parameterizedType = getDefaultParameterizedType( initialType ); } if( parameterizedType.isParameterizedType() ) { for( int i = 0; i < parameterizedType.getTypeParameters().length; i++ ) { IType parameter = parameterizedType.getTypeParameters()[i]; typeParametersByPosition.get( i ).add( parameter ); } } } ArrayList<IType> paramLubs = new ArrayList<IType>(); for( List<IType> paramterTypesAtPositionI : typeParametersByPosition ) { IType leastUpperBound = findLeastUpperBoundImpl( paramterTypesAtPositionI, resolvingTypes ); paramLubs.add( leastUpperBound ); } IType finalType = lub.getParameterizedType( paramLubs.toArray( new IType[paramLubs.size()] ) ); returnSet.add( finalType ); } else { returnSet.add( lub ); } } return returnSet; } private static void pruneNonLUBs( Set<IType> typeSet ) { for( Iterator<IType> outerIterator = typeSet.iterator(); outerIterator.hasNext(); ) { IType typeToPossiblyRemove = outerIterator.next(); for( IType otherType : typeSet ) { //noinspection SuspiciousMethodCalls if( otherType.getAllTypesInHierarchy().contains( typeToPossiblyRemove ) && !typeToPossiblyRemove.getAllTypesInHierarchy().contains( otherType ) ) { outerIterator.remove(); break; } } } } public static boolean isRecursiveType( IJavaType javaType ) { return getDefaultParameterizedType( javaType ).isGenericType(); } public static boolean isRecursiveType( ITypeVariableType subject, IType... types ) { return _isRecursiveType( subject, new HashSet<>(), types ); } private static boolean _isRecursiveType( ITypeVariableType subject, Set<IType> visited, IType... types ) { visited.add( subject ); for( IType csr : types ) { for( IType subj : visited ) { if( getPureGenericType( csr ).equals( getPureGenericType( subj ) ) ) { // Short-circuit recursive type parameterization e.g., class Foo<T extends Foo<T>> return true; } } if( csr instanceof CompoundType ) { Set<IType> compoundTypeComponents = csr.getCompoundTypeComponents(); IType[] typesArr = compoundTypeComponents.toArray( new IType[compoundTypeComponents.size()] ); if( _isRecursiveType( subject, visited, typesArr ) ) { return true; } } else if( csr.isParameterizedType() ) { if( _isRecursiveType( subject, visited, csr.getTypeParameters() ) ) { return true; } } else if( csr.isGenericType() ) { for( IGenericTypeVariable gtv: csr.getGenericTypeVariables() ) { ITypeVariableDefinition tvd = gtv.getTypeVariableDefinition(); if( tvd != null && tvd.getType() != null && _isRecursiveType( subject, visited, tvd.getType() ) ) { return true; } } } else if( csr instanceof TypeVariableType ) { if( !visited.contains( csr ) && _isRecursiveType( (ITypeVariableType)csr, visited, ((TypeVariableType)csr).getBoundingType() ) ) { return true; } visited.remove( csr ); if( _isRecursiveType( subject, visited, ((TypeVariableType)csr).getBoundingType() ) ) { return true; } } else if( csr.isArray() ) { if( _isRecursiveType( subject, visited, csr.getComponentType() ) ) { return true; } } } return false; } public static IJavaClassInfo getOuterMostEnclosingClass(IJavaClassInfo innerClass) { IJavaClassInfo outerMost = innerClass; while( outerMost.getEnclosingType() != null ) { outerMost = outerMost.getEnclosingClass(); } return outerMost; } public static IType getOuterMostEnclosingClass( IType innerClass ) { IType outerMost = innerClass; while( outerMost.getEnclosingType() != null && !isEvalProgram( outerMost ) ) { outerMost = outerMost.getEnclosingType(); if (TypeSystem.isDeleted(outerMost)) { return null; } } return outerMost; } public static boolean isParameterizedType( IType type ) { if( type.isParameterizedType() ) { return true; } if( type instanceof CompoundType ) { for( IType compType : type.getCompoundTypeComponents() ) { if( isParameterizedType( compType ) ) { return true; } } } return false; } public static boolean isEvalProgram( IType type ) { return (type instanceof IGosuProgram) && ((IGosuProgram)type).isAnonymous(); } public static void addReferencedTypeVarsThatAreNotInMap( IType type, TypeVarToTypeMap map ) { if( type instanceof TypeVariableType ) { IType existingType = map.get( (TypeVariableType)type ); if( existingType == null ) { map.put( (ITypeVariableType)type, type ); } } else if( type.isParameterizedType() ) { for( IType typeParam : type.getTypeParameters() ) { addReferencedTypeVarsThatAreNotInMap( typeParam, map ); } } else if( type.isArray() ) { addReferencedTypeVarsThatAreNotInMap( type.getComponentType(), map ); } else if( type instanceof IFunctionType ) { IFunctionType funType = (IFunctionType)type; IType[] types = funType.getParameterTypes(); for( IType iType : types ) { addReferencedTypeVarsThatAreNotInMap( iType, map ); } addReferencedTypeVarsThatAreNotInMap( funType.getReturnType(), map ); } } public static boolean hasTypeVariable( IType type ) { return getTypeVariables( type, tv -> true ); } public static List<ITypeVariableType> getTypeVariables( IType type ) { final List<ITypeVariableType> tvs = new ArrayList<>(); getTypeVariables( type, tv -> {tvs.add( tv ); return false;} ); return tvs; } public static boolean getTypeVariables( IType type, Predicate<ITypeVariableType> cb ) { boolean bRet = false; if( type == null ) { bRet = false; } else if( type instanceof TypeVariableType ) { bRet = cb.test( (ITypeVariableType)type ); } else if( type instanceof TypeVariableArrayType ) { bRet = getTypeVariables( type.getComponentType(), cb ); } else if( type instanceof CompoundType ) { for( IType t: ((CompoundType)type).getTypes() ) { if( getTypeVariables( t, cb ) ) { bRet = true; break; } } } else if( type.isParameterizedType() ) { IType[] compileTimeTypeParams = type.getTypeParameters(); for( int i = 0; i < compileTimeTypeParams.length; i++ ) { IType ctTypeParam = compileTimeTypeParams[i]; if( getTypeVariables( ctTypeParam, cb ) ) { bRet = true; break; } } } return bRet; } public static boolean isExpandable( IType type ) { return getExpandableComponentType( type ) != null; } public static IType getExpandableComponentType( IType type ) { return getExpandableComponentType( type, true ); } public static IType getExpandableComponentType( IType type, boolean bCore ) { Set<IType> visited = new HashSet<IType>(); while( true ) { if( !visited.add( type ) ) { // short-circuit recursive types return type; } if( type.isArray() ) { type = type.getComponentType(); } else if( JavaTypes.INTEGER_INTERVAL().isAssignableFrom( type ) ) { return JavaTypes.pINT(); } else if( JavaTypes.LONG_INTERVAL().isAssignableFrom( type ) ) { return JavaTypes.pLONG(); } else if( type instanceof IPlaceholder && ((IPlaceholder)type).isPlaceholder() ) { return type.getComponentType(); } else { IType parameterized = TypeLord.findParameterizedType( type, JavaTypes.ITERABLE() ); if( parameterized != null && parameterized.isParameterizedType() ) { type = parameterized.getTypeParameters()[0]; } else { parameterized = TypeLord.findParameterizedType( type, JavaTypes.ITERATOR() ); if( parameterized != null && parameterized.isParameterizedType() ) { type = parameterized.getTypeParameters()[0]; } else { return type; } } } if( !bCore ) { return type; } } } public static void inferTypeVariableTypesFromGenParamTypeAndConcreteType( IType genParamType, IType argType, TypeVarToTypeMap inferenceMap ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( genParamType, argType, inferenceMap, new HashSet<ITypeVariableType>(), false ); } public static void inferTypeVariableTypesFromGenParamTypeAndConcreteType_Reverse( IType genParamType, IType argType, TypeVarToTypeMap inferenceMap ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( genParamType, argType, inferenceMap, new HashSet<ITypeVariableType>(), true ); } public static void inferTypeVariableTypesFromGenParamTypeAndConcreteType( IType genParamType, IType argType, TypeVarToTypeMap inferenceMap, HashSet<ITypeVariableType> inferredInCallStack, boolean bReverse ) { if( argType == GosuParserTypes.NULL_TYPE() || argType instanceof IErrorType || (argType instanceof IMetaType && ((IMetaType)argType).getType() instanceof IErrorType) ) { return; } if( argType.isPrimitive() ) { argType = getBoxedTypeFromPrimitiveType(argType); } if( genParamType.isArray() ) { if( !argType.isArray() ) { return; } //## todo: DON'T allow a null component type here; we do it now as a hack that enables gosu arrays to be compatible with java arrays //## todo: same as JavaMethodInfo.inferTypeVariableTypesFromGenParamTypeAndConcreteType() if( argType.getComponentType() == null || !argType.getComponentType().isPrimitive() ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( genParamType.getComponentType(), argType.getComponentType(), inferenceMap, inferredInCallStack, bReverse ); } } else if( genParamType.isParameterizedType() ) { if( argType instanceof FunctionType ) { IFunctionType funcType = genParamType.getFunctionalInterface(); if( funcType != null ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( funcType, argType, inferenceMap, inferredInCallStack, bReverse ); return; } } else if( genParamType instanceof IGosuClass && ((IGosuClass)genParamType).isStructure() ) { if( StandardCoercionManager.isStructurallyAssignable_Laxed( genParamType, argType, inferenceMap ) ) { return; } } IType argTypeInTermsOfParamType = bReverse ? findParameterizedType_Reverse( argType, genParamType ) : findParameterizedType( argType, genParamType.getGenericType() ); if( argTypeInTermsOfParamType == null ) { argTypeInTermsOfParamType = !bReverse ? findParameterizedType_Reverse( argType, genParamType ) : findParameterizedType( argType, genParamType.getGenericType() ); if( argTypeInTermsOfParamType == null ) { return; } } IType[] concreteTypeParams = argTypeInTermsOfParamType.getTypeParameters(); if( concreteTypeParams != null && concreteTypeParams.length > 0 ) { int i = 0; IType[] genTypeParams = genParamType.getTypeParameters(); if( concreteTypeParams.length >= genTypeParams.length ) { for( IType typeArg : genTypeParams ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( typeArg, concreteTypeParams[i++], inferenceMap, inferredInCallStack, bReverse ); } } } } else if( genParamType instanceof ITypeVariableType && argType != GosuParserTypes.NULL_TYPE() ) { ITypeVariableType tvType = ((ITypeVariableType)genParamType).getTypeVarDef().getType(); Pair<IType, Boolean> pair = inferenceMap.getPair( tvType ); IType type = pair == null ? null : pair.getFirst(); boolean pairReverse = pair != null && pair.getSecond(); if( type == null || type instanceof ITypeVariableType ) { // Infer the type inferenceMap.put( tvType, getActualType( argType, inferenceMap, true ), bReverse ); inferredInCallStack.add( tvType ); if( type != null && type.equals( argType ) ) { return; } } else if( type != null ) { IType combinedType = solveType( genParamType, argType, inferenceMap, bReverse || pairReverse, tvType, type ); inferenceMap.put( tvType, combinedType, bReverse ); } IType boundingType = ((ITypeVariableType)genParamType).getBoundingType(); if( !isRecursiveType( (ITypeVariableType)genParamType, boundingType ) ) { inferTypeVariableTypesFromGenParamTypeAndConcreteType( boundingType, argType, inferenceMap, inferredInCallStack, bReverse ); } } else if( genParamType instanceof FunctionType ) { FunctionType genBlockType = (FunctionType)genParamType; if( !(argType instanceof FunctionType) ) { if( argType.isParameterizedType() ) { argType = argType.getFunctionalInterface(); } if( !(argType instanceof FunctionType) ) { return; } } inferTypeVariableTypesFromGenParamTypeAndConcreteType( genBlockType.getReturnType(), ((FunctionType)argType).getReturnType(), inferenceMap, inferredInCallStack, bReverse ); IType[] genBlockParamTypes = genBlockType.getParameterTypes(); if( genBlockParamTypes != null ) { IType[] argTypeParamTypes = ((FunctionType)argType).getParameterTypes(); if( argTypeParamTypes.length == genBlockParamTypes.length ) { for( int i = 0; i < genBlockParamTypes.length; i++ ) { // Infer param types in reverse inferTypeVariableTypesFromGenParamTypeAndConcreteType( genBlockParamTypes[i], ((FunctionType)argType).getParameterTypes()[i], inferenceMap, inferredInCallStack, true ); } } } } } private static IType solveType( IType genParamType, IType argType, TypeVarToTypeMap inferenceMap, boolean bReverse, ITypeVariableType tvType, IType type ) { // Solve the type. Either LUB or GLB. // Infer the type as the intersection of the existing inferred type and this one. This is most relevant for // case where we infer a given type var from more than one type context e.g., a method call: // var l : String // var s : StringBuilder // var r = foo( l, s ) // here we must use the LUB of String and StringBuilder, which is CharSequence & Serializable // function foo<T>( t1: T, t2: T ) {} // Also handle inferring a type from a structure type's methods: IType lubType; if( bReverse ) { // Contravariant lubType = TypeLord.findGreatestLowerBound( type, argType ); } else { if( inferenceMap.isInferredForCovariance( tvType ) ) { // Covariant lubType = argType.equals( genParamType ) ? type : TypeLord.findLeastUpperBound( Arrays.asList( type, argType ) ); } else { // Contravariant // This is the first type encountered in a return/covariant position, the prior type[s] are in contravariant positions, // therefore we can apply contravariance to maintain the return type's more specific type i.e., since the other type[s] // are all param types and are contravariant with tvType, we should keep the more specific type between them. Note if // the param type is more specific, tvType's variance is broken either way (both lub and glb produce a type that is not // call-compatible). lubType = TypeLord.findGreatestLowerBound( type, argType ); } // We have inferred tvType from a covariant position, so we infer using covariance in subsequent positions inferenceMap.setInferredForCovariance( tvType ); } return lubType; } public static IType getConcreteType( IType type ) { if( type.isGenericType() && !type.isParameterizedType() ) { IGenericTypeVariable[] genTypeVars = type.getGenericTypeVariables(); IType[] typeVarTypes = new IType[genTypeVars.length]; for( int i = 0; i < typeVarTypes.length; i++ ) { typeVarTypes[i] = genTypeVars[i].getTypeVariableDefinition().getType(); } type = type.getParameterizedType( typeVarTypes ); } return type; } public static IType getCoreType( IType type ) { if (TypeSystem.isDeleted(type)) { return null; } if( type.isArray() ) { return getCoreType( type.getComponentType() ); } return type; } public static IType getBoxedTypeFromPrimitiveType( IType primitiveType ) { IType boxedType; if( primitiveType == JavaTypes.pBOOLEAN() ) { boxedType = JavaTypes.BOOLEAN(); } else if( primitiveType == JavaTypes.pBYTE() ) { boxedType = JavaTypes.BYTE(); } else if( primitiveType == JavaTypes.pCHAR() ) { boxedType = JavaTypes.CHARACTER(); } else if( primitiveType == JavaTypes.pSHORT() ) { boxedType = JavaTypes.SHORT(); } else if( primitiveType == JavaTypes.pINT() ) { boxedType = JavaTypes.INTEGER(); } else if( primitiveType == JavaTypes.pLONG() ) { boxedType = JavaTypes.LONG(); } else if( primitiveType == JavaTypes.pFLOAT() ) { boxedType = JavaTypes.FLOAT(); } else if( primitiveType == JavaTypes.pDOUBLE() ) { boxedType = JavaTypes.DOUBLE(); } else if( primitiveType == JavaTypes.pVOID() ) { boxedType = JavaTypes.VOID(); } else { throw new IllegalArgumentException( "Unhandled type " + primitiveType ); } return boxedType; } public static IType boundTypes( IType type, List<IType> typesToBound ) { return boundTypes( type, typesToBound, false ); } public static IType boundTypes( IType type, List<IType> typesToBound, boolean bKeepTypeVars ) { IType inferringType; if( type == null ) { return null; } else if( type instanceof ITypeVariableType && (inferringType = inferringType( type, typesToBound, bKeepTypeVars )) != null ) { // inferringType removes type from the list, to prevent stack overflow. IType boundType; if( bKeepTypeVars ) { boundType = inferringType; } else if( isRecursiveType( (ITypeVariableType)type, ((ITypeVariableType)type).getBoundingType() ) && !(((ITypeVariableType)type).getBoundingType() instanceof ITypeVariableType) ) { // short-circuit recursive typevar boundType = TypeLord.getPureGenericType( ((ITypeVariableType)type).getBoundingType() ); } else { boundType = boundTypes( ((ITypeVariableType)type).getBoundingType(), typesToBound, bKeepTypeVars ); } typesToBound.add(inferringType); // add it back return boundType; } else if( type instanceof ITypeVariableArrayType ) { IType componentType = type.getComponentType(); return boundTypes( componentType, typesToBound, bKeepTypeVars ).getArrayType(); } else if( type.isParameterizedType() ) { IType[] typeParameters = type.getTypeParameters(); IType[] parameters = new IType[typeParameters.length]; System.arraycopy( typeParameters, 0, parameters, 0, typeParameters.length ); for( int i = 0; i < parameters.length; i++ ) { parameters[i] = boundTypes( parameters[i], typesToBound, bKeepTypeVars ); } return type.getGenericType().getParameterizedType( parameters ); } else if( type instanceof IFunctionType ) { IFunctionType funType = (IFunctionType)type; IType[] parameterTypes = funType.getParameterTypes(); IType[] paramTypes = new IType[parameterTypes.length]; System.arraycopy( parameterTypes, 0, paramTypes, 0, paramTypes.length ); for( int i = 0; i < paramTypes.length; i++ ) { paramTypes[i] = boundTypes( paramTypes[i], typesToBound, bKeepTypeVars ); } IType returnType = boundTypes( funType.getReturnType(), typesToBound, bKeepTypeVars ); return funType.newInstance( paramTypes, returnType ); } else { return type; } } private static IType inferringType(IType type, List<IType> currentlyInferringTypes, boolean bKeepTypeVars) { if( type instanceof TypeVariableType ) { TypeVariableType typeVarType = (TypeVariableType)type; for( IType currentlyInferringType : currentlyInferringTypes ) { TypeVariableType inferringTypeVarType = (TypeVariableType)currentlyInferringType; if( areTypeVariablesEquivalent( typeVarType, inferringTypeVarType ) ) { if( !bKeepTypeVars ) { currentlyInferringTypes.remove(inferringTypeVarType); } return inferringTypeVarType; } } } return null; } private static boolean areTypeVariablesEquivalent( TypeVariableType possible, TypeVariableType inferred ) { boolean match = false; if( GosuObjectUtil.equals( possible.getName(), inferred.getName() ) ) { IType enclosingType1 = possible.getEnclosingType(); IType enclosingType2 = inferred.getEnclosingType(); if( enclosingType1 instanceof IFunctionType && enclosingType2 instanceof IFunctionType ) { IFunctionType funType1 = (IFunctionType)enclosingType1; IFunctionType funType2 = (IFunctionType)enclosingType2; IScriptPartId id1 = funType1.getScriptPart(); IScriptPartId id2 = funType2.getScriptPart(); String typeName1 = id1 == null ? null : id1.getContainingTypeName(); String typeName2 = id2 == null ? null : id2.getContainingTypeName(); if( GosuObjectUtil.equals( typeName1, typeName2 ) && GosuObjectUtil.equals( funType1.getParamSignature(), funType2.getParamSignature() ) ) { match = true; } } else if( !(enclosingType1 instanceof IFunctionType) && !(enclosingType2 instanceof IFunctionType) ) { match = enclosingType1 == enclosingType2; } } return match; } public static IType getTopLevelType(IType type) { IType topType = getCoreType(type); topType = getPureGenericType(topType); topType = getOuterMostEnclosingClass(topType); return topType; } }
package com.cmput301.cs.project.project.activities; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.cmput301.cs.project.R; import com.cmput301.cs.project.project.model.Claim; import com.cmput301.cs.project.project.utils.Utils; import java.text.DateFormat; public class EditClaimActivity extends Activity { public static final String KEY_CLAIM = "key_claim"; public static Intent intentWithClaim(Context context, Claim claim) { return new Intent(context, EditClaimActivity.class).putExtra(KEY_CLAIM, claim); } private static final int REQ_CODE_PICK_START_DATE = 1; private static final int REQ_CODE_PICK_END_DATE = 2; private Button mStartDate; private Button mEndDate; private Claim.Builder mBuilder; private DateFormat mDateFormat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); Utils.setupDiscardDoneBar(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }, new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_OK, new Intent().putExtra(KEY_CLAIM, mBuilder.build())); finish(); } }); setContentView(R.layout.edit_claim_activity); mDateFormat = android.text.format.DateFormat.getMediumDateFormat(this); mStartDate = (Button) findViewById(R.id.startDate); mEndDate = (Button) findViewById(R.id.endDate); mStartDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final CalendarActivity.Builder builder = new CalendarActivity.Builder(EditClaimActivity.this); if (mBuilder.isStartTimeSet()) { builder.selectedDate(mBuilder.getStartTime()); } if (mBuilder.isEndTimeSet()) { builder.maxDate(mBuilder.getEndTime()); } startActivityForResult(builder.build(), REQ_CODE_PICK_START_DATE); } }); mEndDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final CalendarActivity.Builder builder = new CalendarActivity.Builder(EditClaimActivity.this); if (mBuilder.isEndTimeSet()) { builder.selectedDate(mBuilder.getEndTime()); } if (mBuilder.isStartTimeSet()) { builder.minDate(mBuilder.getStartTime()); } startActivityForResult(builder.build(), REQ_CODE_PICK_END_DATE); } }); initBuilder(); } private void initBuilder() { final Claim claim = getIntent().getParcelableExtra(KEY_CLAIM); if (claim == null) { mBuilder = new Claim.Builder(); } else { mBuilder = Claim.Builder.copyFrom(claim); updateUI(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQ_CODE_PICK_START_DATE: if (resultCode == RESULT_OK) { final long date = data.getLongExtra(CalendarActivity.KEY_DATE, -1); if (date != -1) { mBuilder.startTime(date); updateUI(); } } break; case REQ_CODE_PICK_END_DATE: if (resultCode == RESULT_OK) { final long date = data.getLongExtra(CalendarActivity.KEY_DATE, -1); if (date != -1) { mBuilder.endTime(date); updateUI(); } } break; default: super.onActivityResult(requestCode, resultCode, data); } } private void updateUI() { if (mBuilder.isStartTimeSet()) { mStartDate.setText(mDateFormat.format(mBuilder.getStartTime())); } if (mBuilder.isEndTimeSet()) { mEndDate.setText(mDateFormat.format(mBuilder.getEndTime())); } } }
package pt.c02classes.s01knowledge.s02app.app; import pt.c02classes.s01knowledge.s01base.impl.Statistics; import pt.c02classes.s01knowledge.s01base.inter.IEnquirer; import pt.c02classes.s01knowledge.s01base.inter.IResponder; import pt.c02classes.s01knowledge.s01base.inter.IStatistics; import pt.c02classes.s01knowledge.s01base.inter.IBaseConhecimento; import pt.c02classes.s01knowledge.s02app.actors.EnquirerMaze; import pt.c02classes.s01knowledge.s02app.actors.ResponderMaze; import pt.c02classes.s01knowledge.s01base.impl.BaseConhecimento; import pt.c02classes.s01knowledge.s02app.actors.EnquirerAnimals; import pt.c02classes.s01knowledge.s02app.actors.ResponderAnimals; import java.util.Scanner; public class OrchestratorGeral { /* Implementar um programa para funcionar com os dois jogos; * ele pede por terminal o nome do jogo e o nome do animal * ou do labirinto para realizar o jogo */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); IEnquirer enq; IResponder resp; IStatistics stat; System.out.print("Jogar (A)nimals, (M)aze, ou (S)air? "); String jogo = scanner.nextLine(); while(!jogo.equalsIgnoreCase("F")) { switch (jogo.toUpperCase()) { case "A": IBaseConhecimento base = new BaseConhecimento(); base.setScenario("animals"); String listaAnimais[] = base.listaNomes(); for (String listaAnimai : listaAnimais) { System.out.println("Enquirer com " + listaAnimai + "..."); stat = new Statistics(); resp = new ResponderAnimals(stat, listaAnimai); enq = new EnquirerAnimals(); enq.connect(resp); enq.discover(); System.out.println(" } break; case "M": System.out.println("Escolha o Labirinto: "); System.out.print(" String labirinto = scanner.nextLine(); System.out.printf("Enquirer com %s...%n", labirinto); labirinto = labirinto.toLowerCase(); stat = new Statistics(); resp = new ResponderMaze(stat, labirinto); enq = new EnquirerMaze(); enq.connect(resp); enq.discover(); System.out.println(" break; } System.out.print("Jogar (A)nimals (M)aze, ou (S)air? "); jogo = scanner.nextLine(); } scanner.close(); } }
package io.hawt.system; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.Principal; import java.util.List; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.AccountException; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To perform authentication using JAAS using the {@link LoginContext} for the choosen realm. */ public class Authenticator { private static final transient Logger LOG = LoggerFactory.getLogger(Authenticator.class); public static final String HEADER_AUTHORIZATION = "Authorization"; public static final String AUTHENTICATION_SCHEME_BASIC = "Basic"; private static Boolean websphereDetected; private static Method websphereGetGroupsMethod; public static void extractAuthInfo(String authHeader, ExtractAuthInfoCallback cb) { authHeader = authHeader.trim(); String[] parts = authHeader.split(" "); if (parts.length != 2) { return; } String authType = parts[0]; String authInfo = parts[1]; if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) { String decoded = new String(Base64.decodeBase64(authInfo)); parts = decoded.split(":"); if (parts.length != 2) { return; } String user = parts[0]; String password = parts[1]; cb.getAuthInfo(user, password); } } public static AuthenticateResult authenticate(String realm, String role, String rolePrincipalClasses, Configuration configuration, HttpServletRequest request, PrivilegedCallback cb) { String authHeader = request.getHeader(HEADER_AUTHORIZATION); if (authHeader == null || authHeader.equals("")) { return AuthenticateResult.NO_CREDENTIALS; } final AuthInfo info = new AuthInfo(); Authenticator.extractAuthInfo(authHeader, new ExtractAuthInfoCallback() { @Override public void getAuthInfo(String userName, String password) { info.username = userName; info.password = password; } }); if (info.username == null || info.username.equals("public")) { return AuthenticateResult.NO_CREDENTIALS; } if (info.set()) { Subject subject = doAuthenticate(realm, role, rolePrincipalClasses, configuration, info.username, info.password); if (subject == null) { return AuthenticateResult.NOT_AUTHORIZED; } if (cb != null) { try { cb.execute(subject); } catch (Exception e) { LOG.warn("Failed to execute privileged action: ", e); } } return AuthenticateResult.AUTHORIZED; } return AuthenticateResult.NO_CREDENTIALS; } private static Subject doAuthenticate(String realm, String role, String rolePrincipalClasses, Configuration configuration, final String username, final String password) { try { if (LOG.isDebugEnabled()) { LOG.debug("doAuthenticate[realm={}, role={}, rolePrincipalClasses={}, configuration={}, username={}, password={}]", new Object[]{realm, role, rolePrincipalClasses, configuration, username, "******"}); } Subject subject = new Subject(); CallbackHandler handler = new AuthenticationCallbackHandler(username, password); // call the constructor with or without the configuration as it behaves differently LoginContext loginContext; if (configuration != null) { loginContext = new LoginContext(realm, subject, handler, configuration); } else { loginContext = new LoginContext(realm, subject, handler); } loginContext.login(); if (role == null || role.equals("")) { LOG.debug("Skipping role check, no role configured"); return subject; } if (role.equals("*")) { LOG.debug("Skipping role check, all roles allowed"); return subject; } boolean found; if (isRunningOnWebsphere(subject)) { found = checkIfSubjectHasRequiredRoleOnWebsphere(subject, role); } else { if (rolePrincipalClasses == null || rolePrincipalClasses.equals("")) { LOG.debug("Skipping role check, no rolePrincipalClasses configured"); return subject; } found= checkIfSubjectHasRequiredRole(subject, role,rolePrincipalClasses); } if (!found) { LOG.debug("User " + username + " does not have the required role " + role); return null; } return subject; } catch (AccountException e) { LOG.warn("Account failure", e); } catch (LoginException e) { // do not be so verbose at DEBUG level if (LOG.isTraceEnabled()) { LOG.trace("Login failed due " + e.getMessage(), e); } else { LOG.debug("Login failed due " + e.getMessage()); } } return null; } private static boolean checkIfSubjectHasRequiredRole(Subject subject, String role, String rolePrincipalClasses) { String[] roleArray = role.split(","); String[] rolePrincipalClazzes = rolePrincipalClasses.split(","); boolean found = false; for (String clazz : rolePrincipalClazzes) { LOG.debug("Looking for rolePrincipalClass: {}", clazz); for (Principal p : subject.getPrincipals()) { LOG.debug("Checking principal, classname: {} toString: {}", p.getClass().getName(), p); if (!p.getClass().getName().equals(clazz.trim())) { LOG.debug("principal class {} doesn't match {}, continuing", p.getClass().getName(), clazz.trim()); continue; } for (String r : roleArray) { if (r == null || !p.getName().equals(r.trim())) { LOG.debug("role {} doesn't match {}, continuing", p.getName(), r); continue; } LOG.debug("Matched role and role principal class"); found = true; break; } if (found) { break; } } if (found) { break; } } return found; } private static boolean isRunningOnWebsphere(Subject subject) { if (websphereDetected == null) { boolean onWebsphere = false; for (Principal p : subject.getPrincipals()) { LOG.trace("Checking principal for IBM specific interfaces: {}" , p); onWebsphere = implementsInterface(p, "com.ibm.websphere.security.auth.WSPrincipal" ); } LOG.trace("Checking if we are running using a IBM Websphere specific LoginModule: {}", onWebsphere); websphereDetected = onWebsphere; } return websphereDetected; } private static boolean checkIfSubjectHasRequiredRoleOnWebsphere(Subject subject, String role) { boolean found = false; LOG.debug("Running on websphere: checking if the Role {} is in the set of groups in WSCredential", role); for (final Object cred : subject.getPublicCredentials()) { LOG.debug("Checking credential {} if it is a WebSphere specific WSCredential containing group info", cred); if (implementsInterface(cred, "com.ibm.websphere.security.cred.WSCredential")) { try { Method groupsMethod = getWebSphereGetGroupsMethod(cred); @SuppressWarnings("unchecked") final List<Object> groups = (List<Object>) groupsMethod.invoke(cred); if (groups != null) { LOG.debug("Found a total of {} groups in the IBM WebSphere Credentials", groups.size()); for (Object group : groups) { LOG.debug("Matching IBM Websphere group name {} to required role {}", group, role); if (role.equals(group.toString())) { LOG.debug("Required role {} found in IBM specific credentials", role); found = true; break; } } } else { LOG.debug("The IBM Websphere groups list is null"); } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // ignored LOG.debug("Caught exception trying to read groups from WebSphere specific WSCredentials class", e); } } if (found) { break; } } return found; } private static Method getWebSphereGetGroupsMethod(final Object cred) throws NoSuchMethodException { if (websphereGetGroupsMethod == null) { websphereGetGroupsMethod = cred.getClass().getMethod("getGroupIds"); } return websphereGetGroupsMethod; } private static boolean implementsInterface(Object o, String interfaceName) { boolean implementsIf = false; for (Class<?> pif : o.getClass().getInterfaces()) { LOG.trace("Checking interface {} if it matches {}", pif, interfaceName); if (pif.getName().equals(interfaceName)) { implementsIf = true; break; } } return implementsIf; } private static final class AuthenticationCallbackHandler implements CallbackHandler { private final String username; private final String password; private AuthenticationCallbackHandler(String username, String password) { this.username = username; this.password = password; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (LOG.isTraceEnabled()) { LOG.trace("Callback type {} -> {}", callback.getClass(), callback); } if (callback instanceof NameCallback) { ((NameCallback) callback).setName(username); } else if (callback instanceof PasswordCallback) { ((PasswordCallback) callback).setPassword(password.toCharArray()); } else { LOG.debug("Unknown callback class [" + callback.getClass().getName() + "]"); } } } } }
package com.dmdirc.ui.swing.dialogs.actioneditor; import com.dmdirc.actions.ActionManager; import com.dmdirc.actions.interfaces.ActionType; import com.dmdirc.ui.swing.components.TextLabel; import com.dmdirc.ui.swing.components.renderers.ActionTypeRenderer; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import net.miginfocom.swing.MigLayout; /** * Action triggers panel. */ public class ActionTriggersPanel extends JPanel implements ActionListener, ActionTriggerRemovalListener, PropertyChangeListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** Trigger combo box. */ private JComboBox trigger; /** Add button. */ private JButton add; /** Triggers list. */ private ActionTriggersListPanel triggerList; /** Instantiates the panel. */ public ActionTriggersPanel() { super(); initComponents(); addListeners(); layoutComponents(); } /** Initialises the components. */ private void initComponents() { setBorder(BorderFactory.createTitledBorder(getBorder(), "Triggers")); trigger = new JComboBox(new ActionTypeModel(getFontMetrics(getFont()), ActionManager.getTypeGroups())); //Only fire events on selection not on highlight trigger.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); trigger.setRenderer(new ActionTypeRenderer()); trigger.setPrototypeDisplayValue("Testing"); trigger.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { JComboBox box = (JComboBox) e.getSource(); Object comp = box.getUI().getAccessibleChild(box, 0); if (!(comp instanceof JPopupMenu)) { return; } JComponent scrollPane = (JComponent) ((JPopupMenu) comp).getComponent(0); Dimension size = scrollPane.getPreferredSize(); if (scrollPane instanceof JScrollPane) { size.width = ((ActionTypeModel) trigger.getModel()). getMaxWidth() + (int) ((JScrollPane) scrollPane). getVerticalScrollBar().getPreferredSize().getWidth(); } else { size.width = ((ActionTypeModel) trigger.getModel()).getMaxWidth(); } scrollPane.setPreferredSize(size); scrollPane.setMaximumSize(size); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); add = new JButton("Add"); add.setEnabled(trigger.getSelectedIndex() != -1); triggerList = new ActionTriggersListPanel(); } /** Adds the listeners. */ private void addListeners() { add.addActionListener(this); trigger.addActionListener(this); triggerList.addTriggerListener(this); triggerList.addPropertyChangeListener("triggerCount", this); } /** Lays out the components. */ private void layoutComponents() { setLayout(new MigLayout("fill, pack")); add(new TextLabel("This action will be triggered when any of these events occurs: "), "growx, wrap, spanx"); add(triggerList, "grow, wrap, spanx"); add(trigger, "growx"); add(add, "right"); } /** * Returns the primary trigger for this panel. * * @return Primary trigger or null */ public ActionType getPrimaryTrigger() { if (triggerList.getTriggerCount() == 0) { return null; } return triggerList.getTrigger(0); } /** * Returns the list of triggers. * * @return Trigger list */ public ActionType[] getTriggers() { final List<ActionType> triggers = triggerList.getTriggers(); return triggers.toArray(new ActionType[triggers.size()]); } /** * Sets the triggers. * * @param triggers Sets the triggers. */ void setTriggers(final ActionType[] triggers) { triggerList.clearTriggers(); for (ActionType localTrigger : triggers) { triggerList.addTrigger(localTrigger); } repopulateTriggers(); } /** * {@inheritDoc} * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getSource() == trigger) { add.setEnabled(trigger.getSelectedIndex() != -1); } else { triggerList.addTrigger((ActionType) trigger.getSelectedItem()); repopulateTriggers(); } } /** {@inheritDoc} */ @Override public void triggerRemoved(final ActionType trigger) { repopulateTriggers(); } /** * Repopulates the triggers in the panel. */ private void repopulateTriggers() { SwingUtilities.invokeLater(new Runnable() { /** {@inheritDoc} */ @Override public void run() { ((ActionTypeModel) trigger.getModel()).removeAllElements(); if (triggerList.getTriggerCount() == 0) { ((ActionTypeModel) trigger.getModel()).setTypeGroup(ActionManager.getTypeGroups()); trigger.setEnabled((trigger.getModel().getSize() > 0)); return; } for (ActionType thisType : ActionManager.getCompatibleTypes(triggerList.getTrigger(0))) { final List<ActionType> types = triggerList.getTriggers(); if (!types.contains(thisType)) { ((ActionTypeModel) trigger.getModel()).addElement(thisType); } } trigger.setEnabled(trigger.getModel().getSize() > 0); } }); } /** {@inheritDoc} */ @Override public void setEnabled(final boolean enabled) { triggerList.setEnabled(enabled); add.setEnabled(trigger.getSelectedIndex() != -1); if (trigger.getModel().getSize() > 0 && enabled) { trigger.setEnabled(enabled); } } /** {@inheritDoc} */ @Override public void propertyChange(final PropertyChangeEvent evt) { firePropertyChange("validationResult", (Integer) evt.getOldValue() > 0, (Integer) evt.getNewValue() > 0); } /** Validates the triggers. */ public void validateTriggers() { triggerList.validateTriggers(); } }
package com.google.typography.font.tools.subsetter; import com.google.typography.font.sfntly.Font; import com.google.typography.font.sfntly.Tag; import com.google.typography.font.sfntly.table.core.OS2Table; import com.google.typography.font.sfntly.table.core.OS2Table.UnicodeRange; import java.io.IOException; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; /** * Recalculates some information for the OS2Table. Note that not all info * is recalculated in this class. Some info is calculated in other subsetters, * as they require information from other tables to be calculated. */ public class OS2TableSubsetter extends TableSubsetterImpl { private static final Map<IntegerRange, UnicodeRange> unicodeRanges; static { @SuppressWarnings("unchecked") Map<IntegerRange, UnicodeRange> tUnicodeRanges = new TreeMap<IntegerRange, UnicodeRange>(new IntegerRangeComparator()); tUnicodeRanges.put(new IntegerRange(0x0000, 0x007F), UnicodeRange.BasicLatin); tUnicodeRanges.put(new IntegerRange(0x0080, 0x00FF), UnicodeRange.Latin1Supplement); tUnicodeRanges.put(new IntegerRange(0x0100, 0x017F), UnicodeRange.LatinExtendedA); tUnicodeRanges.put(new IntegerRange(0x0180, 0x024F), UnicodeRange.LatinExtendedB); tUnicodeRanges.put(new IntegerRange(0x0250, 0x02AF), UnicodeRange.IPAExtensions); tUnicodeRanges.put(new IntegerRange(0x1D00, 0x1D7F), UnicodeRange.IPAExtensions); tUnicodeRanges.put(new IntegerRange(0x1D80, 0x1DBF), UnicodeRange.IPAExtensions); tUnicodeRanges.put(new IntegerRange(0x02B0, 0x02FF), UnicodeRange.SpacingModifierLetters); tUnicodeRanges.put(new IntegerRange(0xA700, 0xA71F), UnicodeRange.SpacingModifierLetters); tUnicodeRanges.put(new IntegerRange(0x0300, 0x036F), UnicodeRange.CombiningDiacriticalMarks); tUnicodeRanges.put(new IntegerRange(0x1DC0, 0x1DFF), UnicodeRange.CombiningDiacriticalMarks); tUnicodeRanges.put(new IntegerRange(0x0370, 0x03FF), UnicodeRange.GreekAndCoptic); tUnicodeRanges.put(new IntegerRange(0x2C80, 0x2CFF), UnicodeRange.Coptic); tUnicodeRanges.put(new IntegerRange(0x0400, 0x04FF), UnicodeRange.Cyrillic); tUnicodeRanges.put(new IntegerRange(0x0500, 0x052F), UnicodeRange.Cyrillic); tUnicodeRanges.put(new IntegerRange(0x2DE0, 0x2DFF), UnicodeRange.Cyrillic); tUnicodeRanges.put(new IntegerRange(0xA640, 0xA69F), UnicodeRange.Cyrillic); tUnicodeRanges.put(new IntegerRange(0x0530, 0x058F), UnicodeRange.Armenian); tUnicodeRanges.put(new IntegerRange(0x0590, 0x05FF), UnicodeRange.Hebrew); tUnicodeRanges.put(new IntegerRange(0xA500, 0xA63F), UnicodeRange.Vai); tUnicodeRanges.put(new IntegerRange(0x0600, 0x06FF), UnicodeRange.Arabic); tUnicodeRanges.put(new IntegerRange(0x0750, 0x077F), UnicodeRange.Arabic); tUnicodeRanges.put(new IntegerRange(0x07C0, 0x07FF), UnicodeRange.NKo); tUnicodeRanges.put(new IntegerRange(0x0900, 0x097F), UnicodeRange.Devanagari); tUnicodeRanges.put(new IntegerRange(0x0980, 0x09FF), UnicodeRange.Bengali); tUnicodeRanges.put(new IntegerRange(0x0A00, 0x0A7F), UnicodeRange.Gurmukhi); tUnicodeRanges.put(new IntegerRange(0x0A80, 0x0AFF), UnicodeRange.Gujarati); tUnicodeRanges.put(new IntegerRange(0x0B00, 0x0B7F), UnicodeRange.Oriya); tUnicodeRanges.put(new IntegerRange(0x0B80, 0x0BFF), UnicodeRange.Tamil); tUnicodeRanges.put(new IntegerRange(0x0C00, 0x0C7F), UnicodeRange.Telugu); tUnicodeRanges.put(new IntegerRange(0x0C80, 0x0CFF), UnicodeRange.Kannada); tUnicodeRanges.put(new IntegerRange(0x0D00, 0x0D7F), UnicodeRange.Malayalam); tUnicodeRanges.put(new IntegerRange(0x0E00, 0x0E7F), UnicodeRange.Thai); tUnicodeRanges.put(new IntegerRange(0x0E80, 0x0EFF), UnicodeRange.Lao); tUnicodeRanges.put(new IntegerRange(0x10A0, 0x10FF), UnicodeRange.Georgian); tUnicodeRanges.put(new IntegerRange(0x2D00, 0x2D2F), UnicodeRange.Georgian); tUnicodeRanges.put(new IntegerRange(0x1B00, 0x1B7F), UnicodeRange.Balinese); tUnicodeRanges.put(new IntegerRange(0x1100, 0x11FF), UnicodeRange.HangulJamo); tUnicodeRanges.put(new IntegerRange(0x1E00, 0x1EFF), UnicodeRange.LatinExtendedAdditional); tUnicodeRanges.put(new IntegerRange(0x2C60, 0x2C7F), UnicodeRange.LatinExtendedAdditional); tUnicodeRanges.put(new IntegerRange(0xA720, 0xA7FF), UnicodeRange.LatinExtendedAdditional); tUnicodeRanges.put(new IntegerRange(0x1F00, 0x1FFF), UnicodeRange.GreekExtended); tUnicodeRanges.put(new IntegerRange(0x2000, 0x206F), UnicodeRange.GeneralPunctuation); tUnicodeRanges.put(new IntegerRange(0x2E00, 0x2E7F), UnicodeRange.GeneralPunctuation); tUnicodeRanges.put(new IntegerRange(0x2070, 0x209F), UnicodeRange.SuperscriptsAndSubscripts); tUnicodeRanges.put(new IntegerRange(0x20A0, 0x20CF), UnicodeRange.CurrencySymbols); tUnicodeRanges.put(new IntegerRange(0x20D0, 0x20FF), UnicodeRange.CombiningDiacriticalMarksForSymbols); tUnicodeRanges.put(new IntegerRange(0x2100, 0x214F), UnicodeRange.LetterlikeSymbols); tUnicodeRanges.put(new IntegerRange(0x2150, 0x218F), UnicodeRange.NumberForms); tUnicodeRanges.put(new IntegerRange(0x2190, 0x21FF), UnicodeRange.Arrows); tUnicodeRanges.put(new IntegerRange(0x27F0, 0x27FF), UnicodeRange.Arrows); tUnicodeRanges.put(new IntegerRange(0x2900, 0x297F), UnicodeRange.Arrows); tUnicodeRanges.put(new IntegerRange(0x2B00, 0x2BFF), UnicodeRange.Arrows); tUnicodeRanges.put(new IntegerRange(0x2200, 0x22FF), UnicodeRange.MathematicalOperators); tUnicodeRanges.put(new IntegerRange(0x2A00, 0x2AFF), UnicodeRange.MathematicalOperators); tUnicodeRanges.put(new IntegerRange(0x27C0, 0x27EF), UnicodeRange.MathematicalOperators); tUnicodeRanges.put(new IntegerRange(0x2980, 0x29FF), UnicodeRange.MathematicalOperators); tUnicodeRanges.put(new IntegerRange(0x2300, 0x23FF), UnicodeRange.MiscTechnical); tUnicodeRanges.put(new IntegerRange(0x2400, 0x243F), UnicodeRange.ControlPictures); tUnicodeRanges.put(new IntegerRange(0x2440, 0x245F), UnicodeRange.OCR); tUnicodeRanges.put(new IntegerRange(0x2460, 0x24FF), UnicodeRange.EnclosedAlphanumerics); tUnicodeRanges.put(new IntegerRange(0x2500, 0x257F), UnicodeRange.BoxDrawing); tUnicodeRanges.put(new IntegerRange(0x2580, 0x259F), UnicodeRange.BlockElements); tUnicodeRanges.put(new IntegerRange(0x25A0, 0x25FF), UnicodeRange.GeometricShapes); tUnicodeRanges.put(new IntegerRange(0x2600, 0x26FF), UnicodeRange.MiscSymbols); tUnicodeRanges.put(new IntegerRange(0x2700, 0x27BF), UnicodeRange.Dingbats); tUnicodeRanges.put(new IntegerRange(0x3000, 0x303F), UnicodeRange.CJKSymbolsAndPunctuation); tUnicodeRanges.put(new IntegerRange(0x3040, 0x309F), UnicodeRange.Hiragana); tUnicodeRanges.put(new IntegerRange(0x30A0, 0x30FF), UnicodeRange.Katakana); tUnicodeRanges.put(new IntegerRange(0x31F0, 0x31FF), UnicodeRange.Katakana); tUnicodeRanges.put(new IntegerRange(0x3100, 0x312F), UnicodeRange.Bopomofo); tUnicodeRanges.put(new IntegerRange(0x31A0, 0x31BF), UnicodeRange.Bopomofo); tUnicodeRanges.put(new IntegerRange(0x3130, 0x318F), UnicodeRange.HangulCompatibilityJamo); tUnicodeRanges.put(new IntegerRange(0xA840, 0xA87F), UnicodeRange.Phagspa); tUnicodeRanges.put(new IntegerRange(0x3200, 0x32FF), UnicodeRange.EnclosedCJKLettersAndMonths); tUnicodeRanges.put(new IntegerRange(0x3300, 0x33FF), UnicodeRange.CJKCompatibility); tUnicodeRanges.put(new IntegerRange(0xAC00, 0xD7AF), UnicodeRange.HangulSyllables); tUnicodeRanges.put(new IntegerRange(0xD800, 0xDFFF), UnicodeRange.NonPlane0); tUnicodeRanges.put(new IntegerRange(0x10900, 0x1091F), UnicodeRange.Phoenician); tUnicodeRanges.put(new IntegerRange(0x4E00, 0x9FFF), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0x2E80, 0x2EFF), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0x2F00, 0x2FDF), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0x2FF0, 0x2FFF), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0x3400, 0x4DBF), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0x20000, 0x2A6DF), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0x3190, 0x319F), UnicodeRange.CJKUnifiedIdeographs); tUnicodeRanges.put(new IntegerRange(0xE000, 0xF8FF), UnicodeRange.PrivateUseAreaPlane0); tUnicodeRanges.put(new IntegerRange(0x31C0, 0x31EF), UnicodeRange.CJKStrokes); tUnicodeRanges.put(new IntegerRange(0xF900, 0xFAFF), UnicodeRange.CJKStrokes); tUnicodeRanges.put(new IntegerRange(0x2F800, 0x2FA1F), UnicodeRange.CJKStrokes); tUnicodeRanges.put(new IntegerRange(0xFB00, 0xFB4F), UnicodeRange.AlphabeticPresentationForms); tUnicodeRanges.put(new IntegerRange(0xFB50, 0xFDFF), UnicodeRange.ArabicPresentationFormsA); tUnicodeRanges.put(new IntegerRange(0xFE20, 0xFE2F), UnicodeRange.CombiningHalfMarks); tUnicodeRanges.put(new IntegerRange(0xFE10, 0xFE1F), UnicodeRange.VerticalForms); tUnicodeRanges.put(new IntegerRange(0xFE30, 0xFE4F), UnicodeRange.VerticalForms); tUnicodeRanges.put(new IntegerRange(0xFE50, 0xFE6F), UnicodeRange.SmallFormVariants); tUnicodeRanges.put(new IntegerRange(0xFE70, 0xFEFF), UnicodeRange.ArabicPresentationFormsB); tUnicodeRanges.put(new IntegerRange(0xFF00, 0xFFEF), UnicodeRange.HalfwidthAndFullwidthForms); tUnicodeRanges.put(new IntegerRange(0xFFF0, 0xFFFF), UnicodeRange.Specials); tUnicodeRanges.put(new IntegerRange(0x0F00, 0x0FFF), UnicodeRange.Tibetan); tUnicodeRanges.put(new IntegerRange(0x0700, 0x074F), UnicodeRange.Syriac); tUnicodeRanges.put(new IntegerRange(0x0780, 0x07BF), UnicodeRange.Thaana); tUnicodeRanges.put(new IntegerRange(0x0D80, 0x0DFF), UnicodeRange.Sinhala); tUnicodeRanges.put(new IntegerRange(0x1000, 0x109F), UnicodeRange.Myanmar); tUnicodeRanges.put(new IntegerRange(0x1200, 0x137F), UnicodeRange.Ethiopic); tUnicodeRanges.put(new IntegerRange(0x1380, 0x139F), UnicodeRange.Ethiopic); tUnicodeRanges.put(new IntegerRange(0x2D80, 0x2DDF), UnicodeRange.Ethiopic); tUnicodeRanges.put(new IntegerRange(0x13A0, 0x13FF), UnicodeRange.Cherokee); tUnicodeRanges.put(new IntegerRange(0x1400, 0x167F), UnicodeRange.UnifiedCanadianAboriginalSyllabics); tUnicodeRanges.put(new IntegerRange(0x1680, 0x169F), UnicodeRange.Ogham); tUnicodeRanges.put(new IntegerRange(0x16A0, 0x16FF), UnicodeRange.Runic); tUnicodeRanges.put(new IntegerRange(0x1780, 0x17FF), UnicodeRange.Khmer); tUnicodeRanges.put(new IntegerRange(0x19E0, 0x19FF), UnicodeRange.Khmer); tUnicodeRanges.put(new IntegerRange(0x1800, 0x18AF), UnicodeRange.Mongolian); tUnicodeRanges.put(new IntegerRange(0x2800, 0x28FF), UnicodeRange.BraillePatterns); tUnicodeRanges.put(new IntegerRange(0xA000, 0xA48F), UnicodeRange.YiSyllables); tUnicodeRanges.put(new IntegerRange(0xA490, 0xA4CF), UnicodeRange.YiSyllables); tUnicodeRanges.put(new IntegerRange(0x1700, 0x171F), UnicodeRange.Tagalog); tUnicodeRanges.put(new IntegerRange(0x1720, 0x173F), UnicodeRange.Tagalog); tUnicodeRanges.put(new IntegerRange(0x1740, 0x175F), UnicodeRange.Tagalog); tUnicodeRanges.put(new IntegerRange(0x1760, 0x177F), UnicodeRange.Tagalog); tUnicodeRanges.put(new IntegerRange(0x10300, 0x1032F), UnicodeRange.OldItalic); tUnicodeRanges.put(new IntegerRange(0x10330, 0x1034F), UnicodeRange.Gothic); tUnicodeRanges.put(new IntegerRange(0x10400, 0x1044F), UnicodeRange.Deseret); tUnicodeRanges.put(new IntegerRange(0x1D000, 0x1D0FF), UnicodeRange.MusicalSymbols); tUnicodeRanges.put(new IntegerRange(0x1D100, 0x1D1FF), UnicodeRange.MusicalSymbols); tUnicodeRanges.put(new IntegerRange(0x1D200, 0x1D24F), UnicodeRange.MusicalSymbols); tUnicodeRanges.put(new IntegerRange(0x1D400, 0x1D7FF), UnicodeRange.MathematicalAlphanumericSymbols); tUnicodeRanges.put(new IntegerRange(0xFF000, 0xFFFFD), UnicodeRange.PrivateUsePlane15And16); tUnicodeRanges.put(new IntegerRange(0x100000, 0x10FFFD), UnicodeRange.PrivateUsePlane15And16); tUnicodeRanges.put(new IntegerRange(0xFE00, 0xFE0F), UnicodeRange.VariationSelectors); tUnicodeRanges.put(new IntegerRange(0xE0100, 0xE01EF), UnicodeRange.VariationSelectors); tUnicodeRanges.put(new IntegerRange(0xE0000, 0xE007F), UnicodeRange.Tags); tUnicodeRanges.put(new IntegerRange(0x1900, 0x194F), UnicodeRange.Limbu); tUnicodeRanges.put(new IntegerRange(0x1950, 0x197F), UnicodeRange.TaiLe); tUnicodeRanges.put(new IntegerRange(0x1980, 0x19DF), UnicodeRange.NewTaiLue); tUnicodeRanges.put(new IntegerRange(0x1A00, 0x1A1F), UnicodeRange.Buginese); tUnicodeRanges.put(new IntegerRange(0x2C00, 0x2C5F), UnicodeRange.Glagolitic); tUnicodeRanges.put(new IntegerRange(0x2D30, 0x2D7F), UnicodeRange.Tifnagh); tUnicodeRanges.put(new IntegerRange(0x4DC0, 0x4DFF), UnicodeRange.YijingHexagramSymbols); tUnicodeRanges.put(new IntegerRange(0xA800, 0xA82F), UnicodeRange.SylotiNagari); tUnicodeRanges.put(new IntegerRange(0x10000, 0x1007F), UnicodeRange.LinearB); tUnicodeRanges.put(new IntegerRange(0x10080, 0x100FF), UnicodeRange.LinearB); tUnicodeRanges.put(new IntegerRange(0x10100, 0x1013F), UnicodeRange.LinearB); tUnicodeRanges.put(new IntegerRange(0x10140, 0x1018F), UnicodeRange.AncientGreekNumbers); tUnicodeRanges.put(new IntegerRange(0x10380, 0x1039F), UnicodeRange.Ugaritic); tUnicodeRanges.put(new IntegerRange(0x103A0, 0x103DF), UnicodeRange.OldPersian); tUnicodeRanges.put(new IntegerRange(0x10450, 0x1047F), UnicodeRange.Shavian); tUnicodeRanges.put(new IntegerRange(0x10480, 0x104AF), UnicodeRange.Osmanya); tUnicodeRanges.put(new IntegerRange(0x10800, 0x1083F), UnicodeRange.CypriotSyllabary); tUnicodeRanges.put(new IntegerRange(0x10A00, 0x10A5F), UnicodeRange.Kharoshthi); tUnicodeRanges.put(new IntegerRange(0x1D300, 0x1D35F), UnicodeRange.TaiXuanJingSymbols); tUnicodeRanges.put(new IntegerRange(0x12000, 0x123FF), UnicodeRange.Cuneiform); tUnicodeRanges.put(new IntegerRange(0x12400, 0x1247F), UnicodeRange.Cuneiform); tUnicodeRanges.put(new IntegerRange(0x1D360, 0x1D37F), UnicodeRange.CountingRodNumerals); tUnicodeRanges.put(new IntegerRange(0x1B80, 0x1BBF), UnicodeRange.Sudanese); tUnicodeRanges.put(new IntegerRange(0x1C00, 0x1C4F), UnicodeRange.Lepcha); tUnicodeRanges.put(new IntegerRange(0x1C50, 0x1C7F), UnicodeRange.OlChiki); tUnicodeRanges.put(new IntegerRange(0xA880, 0xA8DF), UnicodeRange.Saurashtra); tUnicodeRanges.put(new IntegerRange(0xA900, 0xA92F), UnicodeRange.KayahLi); tUnicodeRanges.put(new IntegerRange(0xA930, 0xA95F), UnicodeRange.Rejang); tUnicodeRanges.put(new IntegerRange(0xAA00, 0xAA5F), UnicodeRange.Charm); tUnicodeRanges.put(new IntegerRange(0x10190, 0x101CF), UnicodeRange.AncientSymbols); tUnicodeRanges.put(new IntegerRange(0x101D0, 0x101FF), UnicodeRange.PhaistosDisc); tUnicodeRanges.put(new IntegerRange(0x102A0, 0x102DF), UnicodeRange.Carian); tUnicodeRanges.put(new IntegerRange(0x10280, 0x1029F), UnicodeRange.Carian); tUnicodeRanges.put(new IntegerRange(0x10920, 0x1093F), UnicodeRange.Carian); tUnicodeRanges.put(new IntegerRange(0x1F030, 0x1F09F), UnicodeRange.DominoTiles); tUnicodeRanges.put(new IntegerRange(0x1F000, 0x1F02F), UnicodeRange.DominoTiles); unicodeRanges = tUnicodeRanges; } public OS2TableSubsetter() { super(Tag.OS_2); } /** * Determines the OS/2 UniCode range that contains the specified * UniCode character point. * @param unicode The unicode character point to lookup * @return The UnicodeRange that contains the character point, or null if no * such UnicodeRange exists. */ public static UnicodeRange unicodeToRange(int unicode) { return unicodeRanges.get(unicode); } @Override public boolean subset(Subsetter subsetter, Font font, Font.Builder fontBuilder) throws IOException { OS2Table.Builder os2 = (OS2Table.Builder)fontBuilder.getTableBuilder(Tag.OS_2); if (os2 != null) { int fsType = os2.fsTypeAsInt(); //Zero out reserved bits, based on the OS/2 version number. switch (os2.tableVersion()) { case 0: case 1: fsType &= 0xE; break; case 2: case 3: case 4: fsType &= 0x30E; break; } os2.setFsType(fsType); } return true; } private static class IntegerRange implements Comparable { private int min, max; public IntegerRange(int min, int max) { this.min = min; this.max = max; } @Override public int compareTo(Object o) { if (o instanceof Integer) { int value = (Integer) o; if (value < min) return -1; else if (value > max) return 1; else return 0; } else if (o instanceof IntegerRange) { IntegerRange other = (IntegerRange) o; if (other.min < min) return -1; else if (other.max > max) return 1; else return 0; } throw new ClassCastException("Cannot be compared with this type"); } @Override public boolean equals(Object o) { if (o instanceof Integer) { int value = (Integer) o; return value >= min && value <= max; } else if (o instanceof IntegerRange) { IntegerRange other = (IntegerRange) o; return min == other.min && max == other.max; } return false; } } private static class IntegerRangeComparator implements Comparator { @Override public int compare(Object o1, Object o2) { if (o2 instanceof IntegerRange) { IntegerRange range = (IntegerRange) o2; if (o1 instanceof Integer) { int value = (Integer) o1; if (value < range.min) return -1; else if (value > range.max) return 1; else return 0; } else if (o1 instanceof IntegerRange) { IntegerRange other = (IntegerRange) o1; if (other.min < range.min) return -1; else if (other.max > range.max) return 1; else return 0; } } throw new ClassCastException("Cannot be compared with this type"); } } }
package com.opengamma.financial.analytics; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.time.calendar.Clock; import javax.time.calendar.TimeZone; import javax.time.calendar.ZonedDateTime; import org.fudgemsg.FudgeFieldContainer; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.function.FunctionInvoker; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.MarketDataFieldNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.greeks.Greek; import com.opengamma.financial.greeks.GreekResult; import com.opengamma.financial.greeks.GreekResultCollection; import com.opengamma.financial.model.interestrate.curve.DiscountCurve; import com.opengamma.financial.model.option.definition.EuropeanVanillaOptionDefinition; import com.opengamma.financial.model.option.definition.OptionDefinition; import com.opengamma.financial.model.option.definition.StandardOptionDataBundle; import com.opengamma.financial.model.option.pricing.analytic.AnalyticOptionModel; import com.opengamma.financial.model.option.pricing.analytic.BlackScholesMertonModel; import com.opengamma.financial.model.volatility.surface.VolatilitySurface; import com.opengamma.financial.security.AmericanVanillaOption; import com.opengamma.financial.security.EquityOptionSecurity; import com.opengamma.financial.security.EuropeanVanillaOption; import com.opengamma.financial.security.OptionType; import com.opengamma.financial.security.OptionVisitor; import com.opengamma.financial.security.PoweredOption; import com.opengamma.util.time.DateUtil; import com.opengamma.util.time.Expiry; /** * * * @author jim */ public class EquityOptionGreeksFunction extends AbstractFunction implements FunctionInvoker { private static final Map<String, Greek> s_greeksByValueName; static { Map<String, Greek> greeksMap = new TreeMap<String,Greek>(); greeksMap.put(ValueRequirementNames.FAIR_VALUE, Greek.PRICE); greeksMap.put(ValueRequirementNames.DELTA, Greek.DELTA); greeksMap.put(ValueRequirementNames.GAMMA, Greek.GAMMA); greeksMap.put(ValueRequirementNames.RHO, Greek.RHO); s_greeksByValueName = Collections.unmodifiableMap(greeksMap); } @Override public String getShortName() { return "Equity Option Greeks Analytic Function"; } // NewFunction* Methods: @Override public boolean canApplyTo(FunctionCompilationContext context, ComputationTarget target) { return canApplyTo(target); } protected boolean canApplyTo(ComputationTarget target) { if(target.getType() != ComputationTargetType.SECURITY) { return false; } if(!(target.getValue() instanceof EquityOptionSecurity)) { return false; } EquityOptionSecurity equityOptionSec = (EquityOptionSecurity) target.getSecurity(); Boolean canApply = equityOptionSec.accept(new OptionVisitor<Boolean>() { @Override public Boolean visitAmericanVanillaOption(AmericanVanillaOption option) { return true; } @Override public Boolean visitEuropeanVanillaOption(EuropeanVanillaOption option) { return true; } @Override public Boolean visitPoweredOption(PoweredOption option) { return true; } }); return canApply; } @Override public Set<ValueRequirement> getRequirements(FunctionCompilationContext context, ComputationTarget target) { if(!canApplyTo(context, target)) { return null; } EquityOptionSecurity equityOptionSec = (EquityOptionSecurity)target.getSecurity(); ValueRequirement discountCurveReq = new ValueRequirement(ValueRequirementNames.DISCOUNT_CURVE, ComputationTargetType.PRIMITIVE, equityOptionSec.getCurrency().getISOCode()); ValueRequirement volatilitySurfaceReq = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE, ComputationTargetType.SECURITY, equityOptionSec.getIdentityKey()); ValueRequirement underlyingMarketDataReq = new ValueRequirement(ValueRequirementNames.MARKET_DATA_HEADER, ComputationTargetType.SECURITY, equityOptionSec.getUnderlyingIdentityKey()); // No need to do a visitor as of this stage. Set<ValueRequirement> requirements = new HashSet<ValueRequirement>(); requirements.add(discountCurveReq); requirements.add(volatilitySurfaceReq); requirements.add(underlyingMarketDataReq); return requirements; } @Override public Set<ValueSpecification> getResults(FunctionCompilationContext context, ComputationTarget target, Set<ValueRequirement> requirements) { if(!canApplyTo(context, target)) { return null; } EquityOptionSecurity equityOptionSec = (EquityOptionSecurity)target.getSecurity(); Set<ValueSpecification> results = new HashSet<ValueSpecification>(); for(ValueRequirement requirement : requirements) { if(requirement.getTargetSpecification().getType() != ComputationTargetType.SECURITY) { continue; } if(s_greeksByValueName.containsKey(requirement.getValueName())) { results.add(new ValueSpecification(new ValueRequirement(requirement.getValueName(), ComputationTargetType.SECURITY, equityOptionSec.getIdentityKey()))); } } return results; } @Override public Set<ComputedValue> execute( FunctionExecutionContext executionContext, FunctionInputs inputs, ComputationTarget target) { if(!canApplyTo(target)) { return null; } // Gather Inputs: EquityOptionSecurity equityOptionSec = (EquityOptionSecurity)target.getSecurity(); DiscountCurve discountCurve = (DiscountCurve)inputs.getValue(ValueRequirementNames.DISCOUNT_CURVE); VolatilitySurface volatilitySurface = (VolatilitySurface)inputs.getValue(ValueRequirementNames.VOLATILITY_SURFACE); ValueRequirement underlyingMarketDataReq = new ValueRequirement(ValueRequirementNames.MARKET_DATA_HEADER, ComputationTargetType.SECURITY, equityOptionSec.getUnderlyingIdentityKey()); FudgeFieldContainer underlyingMarketData = (FudgeFieldContainer)inputs.getValue(underlyingMarketDataReq); // Perform Calculation: final ZonedDateTime today = Clock.system(TimeZone.UTC).zonedDateTime(); final Expiry expiry = equityOptionSec.getExpiry(); final double costOfCarry_b = discountCurve.getInterestRate(DateUtil.getDifferenceInYears(today, expiry.getExpiry().toInstant())); final double spot = underlyingMarketData.getDouble(MarketDataFieldNames.INDICATIVE_VALUE_NAME); StandardOptionDataBundle bundle = new StandardOptionDataBundle(discountCurve, costOfCarry_b, volatilitySurface, spot, today); EuropeanVanillaOptionDefinition definition = new EuropeanVanillaOptionDefinition(equityOptionSec.getStrike(), expiry, equityOptionSec.getOptionType() == OptionType.CALL); AnalyticOptionModel<OptionDefinition, StandardOptionDataBundle> model = new BlackScholesMertonModel(); GreekResultCollection greeks = model.getGreeks(definition, bundle, Arrays.asList(new Greek[] {Greek.PRICE, Greek.DELTA, Greek.GAMMA, Greek.RHO})); // Translate and package results GreekResult<?> priceResult = greeks.get(Greek.PRICE); GreekResult<?> deltaResult = greeks.get(Greek.DELTA); GreekResult<?> gammaResult = greeks.get(Greek.GAMMA); GreekResult<?> rhoResult = greeks.get(Greek.RHO); ValueSpecification priceSpecification = new ValueSpecification(new ValueRequirement(ValueRequirementNames.FAIR_VALUE, ComputationTargetType.SECURITY, equityOptionSec.getIdentityKey())); ValueSpecification deltaSpecification = new ValueSpecification(new ValueRequirement(ValueRequirementNames.DELTA, ComputationTargetType.SECURITY, equityOptionSec.getIdentityKey())); ValueSpecification gammaSpecification = new ValueSpecification(new ValueRequirement(ValueRequirementNames.GAMMA, ComputationTargetType.SECURITY, equityOptionSec.getIdentityKey())); ValueSpecification rhoSpecification = new ValueSpecification(new ValueRequirement(ValueRequirementNames.RHO, ComputationTargetType.SECURITY, equityOptionSec.getIdentityKey())); ComputedValue priceValue = new ComputedValue(priceSpecification, priceResult.getResult()); ComputedValue deltaValue = new ComputedValue(deltaSpecification, deltaResult.getResult()); ComputedValue gammaValue = new ComputedValue(gammaSpecification, gammaResult.getResult()); ComputedValue rhoValue = new ComputedValue(rhoSpecification, rhoResult.getResult()); Set<ComputedValue> results = new HashSet<ComputedValue>(); results.add(priceValue); results.add(deltaValue); results.add(gammaValue); results.add(rhoValue); return results; } @Override public ComputationTargetType getTargetType() { return ComputationTargetType.SECURITY; } }
package org.openqa.selenium.android.app; public final class R { public static final class attr { } public static final class drawable { public static final int alert_dialog_icon=0x7f020000; public static final int ic_menu_add=0x7f020001; public static final int ic_menu_delete=0x7f020002; public static final int ic_menu_share=0x7f020003; public static final int selenium_icon=0x7f020004; } public static final class id { public static final int rssWebView=0x7f070002; public static final int status=0x7f070000; public static final int webview=0x7f070001; } public static final class layout { public static final int single_session_layout=0x7f030000; } public static final class raw { public static final int javascript_xpath=0x7f050000; } public static final class string { public static final int ctx_menu_navigate=0x7f060001; public static final int default_session_status=0x7f060002; public static final int jetty_already_started=0x7f060005; public static final int jetty_not_running=0x7f060008; public static final int jetty_not_started=0x7f060004; public static final int jetty_not_stopped=0x7f060007; public static final int jetty_started=0x7f060003; public static final int jetty_stopped=0x7f060006; public static final int main_title=0x7f060000; } public static final class xml { public static final int preferences=0x7f040000; } }
package de.mrapp.android.adapter.list.itemstate; import java.util.Collection; /** * Defines the interface, an adapter, whose underlying data is managed as a list * of arbitrary items, which may have different states, must implement. Such an * adapter's purpose is to provide the underlying data for visualization using a * {@link ListView} widget. * * @param <DataType> * The type of the adapter's underlying data * * @author Michael Rapp * * @since 1.0.0 */ public interface ItemStateListAdapter<DataType> { /** * Returns the number of states, the adapter's items may have. * * @return The number of states, the adapter's items may have, as an * {@link Integer} value. The value must be at least 1 */ int getNumberOfItemStates(); void setNumberOfItemStates(int numberOfItemStates); /** * Returns the minimum state, the adapter's items may have. * * @return The minimum state, the adapter's items may have, as an * {@link Integer} value */ int minItemState(); /** * Returns the maximum state, the adapter's items may have. * * @return The maximum state, the adapter's items may have, as an * {@link Integer} value */ int maxItemState(); /** * Returns the current state of the item, which belongs to a specific index. * * @param index * The index of the item, whose state should be returned, as an * {@link Integer} value. The index must be between 0 and the * value of the method <code>getNumberOfItems():int</code> - 1, * otherwise an {@link IndexOutOfBoundsException} will be thrown * @return The state of the item, which belongs to the given index, as a * {@link Integer} value */ int getItemState(int index); /** * Returns the current state of a specific item. * * @param item * The item, whose state should be returned, as an instance of * the generic type DataType. The item may not be null. If the * item does not belong to the adapter, a * {@link NoSuchElementException} will be thrown * @return The state of the given item as an {@link Integer} value */ int getItemState(DataType item); int setItemState(int index, int state); int setItemState(DataType item, int state); boolean setAllItemStates(int state); /** * Triggers the state of the item, which belongs to a specific index, if it * is currently enabled. This causes the state to be increased by one. If * the state is already the maximum state, the state will be set to 0 * instead. * * @param index * The index of the item, whose state should be triggered, as an * {@link Integer} value. The index must be between 0 and the * value of the method <code>getNumberOfItems():int</code> - 1, * otherwise an {@link IndexOutOfBoundsException} will be thrown * @return The previous state of the item, which belongs to the given index, * as an {@link Integer} value or -1, if the state has not been * changed */ int triggerItemState(int index); /** * Triggers the state of a specific item, if it is currently enabled. This * causes the state to be increased by one. If the state is already the * maximum state, the state will be set to 0 instead. * * @param item * The item, whose state should be triggered, as an instance of * the generic type DataType. The item may not be null. If the * item does not belong to the adapter, a * {@link NoSuchElementException} will be thrown * @return The previous state of the given item, as an {@link Integer} value * or -1, if the state has not been changed */ int triggerItemState(DataType item); /** * Triggers the states of all items. if they are currently enabled. This * causes the states to be increased by one. If a state is already the * maximum state, the state will be set to 0 instead. * * @return True, if the states of all items have been changed, false * otherwise */ boolean triggerAllItemStates(); /** * Returns the index of the first item, which currently has a specific * state. * * @param state * The state of the item, whose index should be returned, as an * {@link Integer} value * @return The index of the first item, which currently has the given state, * as an {@link Integer} value or -1, if the adapter does not * contain an item with the given state */ int getFirstIndexWithSpecificState(int state); /** * Returns the first item, which currently has a specific state. * * @param state * The state of the item, which should be returned, as an * {@link Integer} value * @return The first item, which currently has the given state, as an * instance of the generic type DataType or null, if the adapter * does not contain an item with the given state */ DataType getFirstItemWithSpecificState(int state); /** * Returns the index of the last item, which currently has a specific state. * * @param state * The state of the item, whose index should be returned, as an * {@link Integer} value * @return The index of the last item, which currently has the given state, * as an {@link Integer} value or -1, if the adapter does not * contain an item with the given state */ int getLastIndexWithSpecificState(int state); /** * Returns the last item, which currently has a specific state. * * @param state * The state of the item, which should be returned, as an * {@link Integer} value * @return The last item, which currently has the given state, as an * instance of the generic type DataType or null, if the adapter * does not contain an item with the given state */ DataType getLastItemWithSpecificState(int state); /** * Returns a collection, which contains the indices of all items, which * currently have a specific state. * * @param state * The state of the items, whose indices should be returned, as * an {@link Integer} value * @return A collection, which contains the indices of all items, which * currently have a specific state, as an instance of the type * {@link Collection} or an empty collection, if the adapter does * not contain any items with the given state */ Collection<Integer> getIndicesWithSpecificState(int state); /** * Returns a collection, which contains all items, which currently have a * specific state. * * @param state * The state of the items, which should be returned, as an * {@link Integer} value * @return A collection, which contains the items, which currently have the * given state, as an instance of the type {@link Collection} or an * empty collection, if the adapter contains no items with the given * state */ Collection<DataType> getItemsWithSpecificState(int state); /** * Returns the number of items, which currently have a specific state. * * @param state * The state of the items, which should be counted, as an * {@link Integer} value * @return The number of items, which currently have the given state, as an * {@link Integer} value */ int getNumberOfItemsWithSpecificState(int state); /** * Returns, whether the state of an item is triggered, when it is clicked by * the user, or not. * * @return True, if the state of an item is triggered, when it is clicked by * the user, false otherwise */ boolean isItemStateTriggeredOnClick(); /** * Sets, whether the state of an item should be triggered, when it is * clicked by the user, or not. * * @param triggerItemStateOnClick * True, if the state of an item should be triggered, when it is * clicked by the user, false otherwise */ void triggerItemStateOnClick(boolean triggerItemStateOnClick); /** * Adds a new listener, which should be notified, when the state of an item * has been changed. * * @param listener * The listener, which should be added, as an instance of the * class {@link ListItemStateListener}. The listener may not be * null */ void addItemStateListener(final ListItemStateListener<DataType> listener); /** * Removes a specific listener, which should not be notified, when the state * of an item has been changed, anymore. * * @param listener * The listener, which should be removed, as an instance of the * class {@link ListItemStateListener}. The listener may not be * null */ void removeItemStateListener(ListItemStateListener<DataType> listener); }
package com.mapzen.tangram; import android.content.Context; import android.content.res.AssetManager; import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView.Renderer; import android.util.DisplayMetrics; import com.mapzen.tangram.TouchInput.Gestures; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import okio.BufferedSource; public class MapController implements Renderer { public enum EaseType { LINEAR, CUBIC, QUINT, SINE, } protected static EaseType DEFAULT_EASE_TYPE = EaseType.CUBIC; public enum DebugFlag { FREEZE_TILES, PROXY_COLORS, TILE_BOUNDS, TILE_INFOS, LABELS, TANGRAM_INFOS, ALL_LABELS, } public interface FeaturePickListener { /** * Receive information about features found in a call to {@link #pickFeature(float, float)} * @param properties A mapping of string keys to string or number values * @param positionX The horizontal screen coordinate of the center of the feature * @param positionY The vertical screen coordinate of the center of the feature */ void onFeaturePick(Map<String, String> properties, float positionX, float positionY); } /** * Construct a MapController using a custom scene file * @param context Context in which the map will function; the asset bundle for this activity * must contain all the local files that the map will need * @param sceneFilePath Location of the YAML scene file within the assets directory */ MapController(Context context, String sceneFilePath) { scenePath = sceneFilePath; // Get configuration info from application displayMetrics = context.getResources().getDisplayMetrics(); assetManager = context.getAssets(); // Load the fonts fontFileParser = new FontFileParser(); fontFileParser.parse("/system/etc/fonts.xml"); // Set a default HTTPHandler httpHandler = new HttpHandler(); nativeInit(this, assetManager, scenePath); } /** * Set the view in which the map will be drawn * @param view GLSurfaceView where the map will be displayed; input events from this view will * be handled by the resulting MapController */ void setView(GLSurfaceView view) { touchInput = new TouchInput(view.getContext()); setPanResponder(null); setScaleResponder(null); setRotateResponder(null); setShoveResponder(null); touchInput.setSimultaneousDetectionAllowed(Gestures.SHOVE, Gestures.ROTATE, false); touchInput.setSimultaneousDetectionAllowed(Gestures.ROTATE, Gestures.SHOVE, false); touchInput.setSimultaneousDetectionAllowed(Gestures.SHOVE, Gestures.SCALE, false); touchInput.setSimultaneousDetectionAllowed(Gestures.SHOVE, Gestures.PAN, false); touchInput.setSimultaneousDetectionAllowed(Gestures.SCALE, Gestures.LONG_PRESS, false); // Set up MapView mapView = view; view.setOnTouchListener(touchInput); view.setRenderer(this); view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); } /** * Load a new scene file * @param path Location of the YAML scene file within the application assets */ public void loadSceneFile(String path) { scenePath = path; nativeLoadScene(path); requestRender(); } /** * Set the {@link HttpHandler} for retrieving remote map resources; a default-constructed * HttpHandler is suitable for most cases, but methods can be extended to modify resource URLs * @param handler the HttpHandler to use */ public void setHttpHandler(HttpHandler handler) { this.httpHandler = handler; } /** * Set the geographic position of the center of the map view * @param position LngLat of the position to set */ public void setPosition(LngLat position) { nativeSetPosition(position.longitude, position.latitude); } /** * Set the geographic position of the center of the map view * @param position LngLat of the position to set * @param duration Time in milliseconds to ease to the given position */ public void setPosition(LngLat position, int duration) { setPosition(position, duration, DEFAULT_EASE_TYPE); } /** * Set the geographic position of the center of the map view * @param position LngLat of the position to set * @param duration Time in milliseconds to ease to the given position * @param ease Type of easing to use */ public void setPosition(LngLat position, int duration, EaseType ease) { float seconds = duration / 1000.f; nativeSetPositionEased(position.longitude, position.latitude, seconds, ease.ordinal()); } /** * Get the geographic position of the center of the map view * @return The current map position in a LngLat */ public LngLat getPosition() { return getPosition(new LngLat()); } /** * Get the geographic position of the center of the map view * @param out LngLat to be reused as the output * @return Degrees longitude and latitude of the current map position, in a two-element array */ public LngLat getPosition(LngLat out) { double[] tmp = { 0, 0 }; nativeGetPosition(tmp); return out.set(tmp[0], tmp[1]); } /** * Set the zoom level of the map view * @param zoom Fractional zoom level */ public void setZoom(float zoom) { nativeSetZoom(zoom); } /** * Set the zoom level of the map view * @param zoom Fractional zoom level * @param duration Time in milliseconds to ease to given zoom */ public void setZoom(float zoom, int duration) { setZoom(zoom, duration, DEFAULT_EASE_TYPE); } /** * Set the zoom level of the map view * @param zoom Fractional zoom level * @param duration Time in milliseconds to ease to given zoom * @param ease Type of easing to use */ public void setZoom(float zoom, int duration, EaseType ease) { float seconds = duration / 1000.f; nativeSetZoomEased(zoom, seconds, ease.ordinal()); } /** * Get the zoom level of the map view * @return Fractional zoom level */ public float getZoom() { return nativeGetZoom(); } /** * Set the counter-clockwise rotation of the view in radians; 0 corresponds to North pointing up * @param radians Rotation in radians */ public void setRotation(float radians) { nativeSetRotation(radians); } /** * Set the counter-clockwise rotation of the view in radians; 0 corresponds to North pointing up * @param radians Rotation in radians * @param duration Time in milliseconds to ease to the given rotation */ public void setRotation(float radians, int duration) { setRotation(radians, duration, DEFAULT_EASE_TYPE); } /** * Set the counter-clockwise rotation of the view in radians; 0 corresponds to North pointing up * @param radians Rotation in radians * @param duration Time in milliseconds to ease to the given rotation * @param ease Type of easing to use */ public void setRotation(float radians, int duration, EaseType ease) { float seconds = duration / 1000.f; nativeSetRotationEased(radians, seconds, ease.ordinal()); } /** * Get the counter-clockwise rotation of the view in radians; 0 corresponds to North pointing up * @return Rotation in radians */ public float getRotation() { return nativeGetRotation(); } /** * Set the tilt angle of the view in radians; 0 corresponds to straight down * @param radians Tilt angle in radians */ public void setTilt(float radians) { nativeSetTilt(radians); } /** * Set the tilt angle of the view in radians; 0 corresponds to straight down * @param radians Tilt angle in radians * @param duration Time in milliseconds to ease to the given tilt */ public void setTilt(float radians, int duration) { setTilt(radians, duration, DEFAULT_EASE_TYPE); } /** * Set the tilt angle of the view in radians; 0 corresponds to straight down * @param radians Tilt angle in radians * @param duration Time in milliseconds to ease to the given tilt * @param ease Type of easing to use */ public void setTilt(float radians, int duration, EaseType ease) { float seconds = duration / 1000.f; nativeSetTiltEased(radians, seconds, ease.ordinal()); } /** * Get the tilt angle of the view in radians; 0 corresponds to straight down * @return Tilt angle in radians */ public float getTilt() { return nativeGetTilt(); } /** * Find the geographic coordinates corresponding to the given position on screen * @param screenX Pixels from the left edge of the screen * @param screenY Pixels from the top edge of the screen * @return LngLat corresponding to the given point */ public LngLat coordinatesAtScreenPosition(double screenX, double screenY) { double[] tmp = { screenX, screenY }; nativeScreenToWorldCoordinates(tmp); return new LngLat(tmp[0], tmp[1]); } /** * Construct a collection of drawable map features. * @param name The name of the data collection. Once added to a map, features from this * {@code MapData} will be available from a data source with this name, just like a data source * specified in a scene file. You cannot create more than one data source with the same name. * If you call {@code addDataLayer} with the same name more than once, the same {@code MapData} * object will be returned. */ public MapData addDataLayer(String name) { MapData mapData = clientDataSources.get(name); if (mapData != null) { return mapData; } long pointer = nativeAddDataSource(name); if (pointer <= 0) { throw new RuntimeException("Unable to create new data source"); } mapData = new MapData(name, pointer, this); clientDataSources.put(name, mapData); return mapData; } /** * For package-internal use only; remove a {@code MapData} from this map * @param mapData The {@code MapData} to remove */ void removeDataLayer(MapData mapData) { clientDataSources.remove(mapData.name); nativeRemoveDataSource(mapData.pointer); } /** * Manually trigger a re-draw of the map view * * Typically this does not need to be called from outside Tangram, see {@link #setRenderMode(int)}. */ public void requestRender() { mapView.requestRender(); } /** * Set whether the map view re-draws continuously * * Typically this does not need to be called from outside Tangram. The map automatically re-renders when the view * changes or when any animation in the map requires rendering. * @param renderMode Either 1, to render continuously, or 0, to render only when needed. */ public void setRenderMode(int renderMode) { mapView.setRenderMode(renderMode); } /** * Set a responder for tap gestures * @param responder TapResponder to call */ public void setTapResponder(final TouchInput.TapResponder responder) { touchInput.setTapResponder(new TouchInput.TapResponder() { @Override public boolean onSingleTapUp(float x, float y) { return responder != null && responder.onSingleTapUp(x, y); } @Override public boolean onSingleTapConfirmed(float x, float y) { return responder != null && responder.onSingleTapConfirmed(x, y); } }); } /** * Set a responder for double-tap gestures * @param responder DoubleTapResponder to call */ public void setDoubleTapResponder(final TouchInput.DoubleTapResponder responder) { touchInput.setDoubleTapResponder(new TouchInput.DoubleTapResponder() { @Override public boolean onDoubleTap(float x, float y) { return responder != null && responder.onDoubleTap(x, y); } }); } /** * Set a responder for long press gestures * @param responder LongPressResponder to call */ public void setLongPressResponder(final TouchInput.LongPressResponder responder) { touchInput.setLongPressResponder(new TouchInput.LongPressResponder() { @Override public void onLongPress(float x, float y) { if (responder != null) { responder.onLongPress(x, y); } } }); } /** * Set a responder for pan gestures * @param responder PanResponder to call; if onPan returns true, normal panning behavior will not occur */ public void setPanResponder(final TouchInput.PanResponder responder) { touchInput.setPanResponder(new TouchInput.PanResponder() { @Override public boolean onPan(float startX, float startY, float endX, float endY) { if (responder == null || !responder.onPan(startX, startY, endX, endY)) { nativeHandlePanGesture(startX, startY, endX, endY); } return true; } @Override public boolean onFling(float posX, float posY, float velocityX, float velocityY) { if (responder == null || !responder.onFling(posX, posY, velocityX, velocityY)) { nativeHandleFlingGesture(posX, posY, velocityX, velocityY); } return true; } }); } /** * Set a responder for rotate gestures * @param responder RotateResponder to call; if onRotate returns true, normal rotation behavior will not occur */ public void setRotateResponder(final TouchInput.RotateResponder responder) { touchInput.setRotateResponder(new TouchInput.RotateResponder() { @Override public boolean onRotate(float x, float y, float rotation) { if (responder == null || !responder.onRotate(x, y, rotation)) { nativeHandleRotateGesture(x, y, rotation); } return true; } }); } /** * Set a responder for scale gestures * @param responder ScaleResponder to call; if onScale returns true, normal scaling behavior will not occur */ public void setScaleResponder(final TouchInput.ScaleResponder responder) { touchInput.setScaleResponder(new TouchInput.ScaleResponder() { @Override public boolean onScale(float x, float y, float scale, float velocity) { if (responder == null || !responder.onScale(x, y, scale, velocity)) { nativeHandlePinchGesture(x, y, scale, velocity); } return true; } }); } /** * Set a responder for shove (vertical two-finger drag) gestures * @param responder ShoveResponder to call; if onShove returns true, normal tilting behavior will not occur */ public void setShoveResponder(final TouchInput.ShoveResponder responder) { touchInput.setShoveResponder(new TouchInput.ShoveResponder() { @Override public boolean onShove(float distance) { if (responder == null || !responder.onShove(distance)) { nativeHandleShoveGesture(distance); } return true; } }); } /** * Set whether the gesture {@code second} can be recognized while {@code first} is in progress * @param first Initial gesture type * @param second Subsequent gesture type * @param allowed True if {@code second} should be recognized, else false */ public void setSimultaneousGestureAllowed(Gestures first, Gestures second, boolean allowed) { touchInput.setSimultaneousDetectionAllowed(first, second, allowed); } /** * Get whether the gesture {@code second} can be recognized while {@code first} is in progress * @param first Initial gesture type * @param second Subsequent gesture type * @return True if {@code second} will be recognized, else false */ public boolean isSimultaneousGestureAllowed(Gestures first, Gestures second) { return touchInput.isSimultaneousDetectionAllowed(first, second); } /** * Set a listener for feature pick events * @param listener Listener to call */ public void setFeaturePickListener(FeaturePickListener listener) { featurePickListener = listener; } /** * Query the map for labeled features at the given screen coordinates; results will be returned * in a callback to the object set by {@link #setFeaturePickListener(FeaturePickListener)} * @param posX The horizontal screen coordinate * @param posY The vertical screen coordinate */ public void pickFeature(float posX, float posY) { if (featurePickListener != null) { nativePickFeature(posX, posY, featurePickListener); } } /** * Enqueue a Runnable to be executed synchronously on the rendering thread * @param r Runnable to run */ public void queueEvent(Runnable r) { mapView.queueEvent(r); } /** * Make a debugging feature active or inactive * @param flag The feature to set * @param on True to activate the feature, false to deactivate */ public void setDebugFlag(DebugFlag flag, boolean on) { nativeSetDebugFlag(flag.ordinal(), on); } /** * Enqueuee a scene component update with its corresponding YAML node value * @param componentPath The YAML component path delimited by a '.' (example "scene.animated") * @param value A YAML valid string (example "{ property: true }" or "true") */ public void queueSceneUpdate(String componentPath, String value) { nativeQueueSceneUpdate(componentPath, value); } /* * Dispatch scene updates queued by qeueSceneUpdate, and update the scene accordingly */ public void applySceneUpdates() { nativeApplySceneUpdates(); } // Native methods static { System.loadLibrary("c++_shared"); System.loadLibrary("tangram"); } private synchronized native void nativeInit(MapController instance, AssetManager assetManager, String stylePath); private synchronized native void nativeLoadScene(String path); private synchronized native void nativeSetupGL(); private synchronized native void nativeResize(int width, int height); private synchronized native void nativeUpdate(float dt); private synchronized native void nativeRender(); private synchronized native void nativeSetPosition(double lon, double lat); private synchronized native void nativeSetPositionEased(double lon, double lat, float seconds, int ease); private synchronized native void nativeGetPosition(double[] lonLatOut); private synchronized native void nativeSetZoom(float zoom); private synchronized native void nativeSetZoomEased(float zoom, float seconds, int ease); private synchronized native float nativeGetZoom(); private synchronized native void nativeSetRotation(float radians); private synchronized native void nativeSetRotationEased(float radians, float seconds, int ease); private synchronized native float nativeGetRotation(); private synchronized native void nativeSetTilt(float radians); private synchronized native void nativeSetTiltEased(float radians, float seconds, int ease); private synchronized native float nativeGetTilt(); private synchronized native void nativeScreenToWorldCoordinates(double[] screenCoords); private synchronized native void nativeSetPixelScale(float scale); private synchronized native void nativeHandleTapGesture(float posX, float posY); private synchronized native void nativeHandleDoubleTapGesture(float posX, float posY); private synchronized native void nativeHandlePanGesture(float startX, float startY, float endX, float endY); private synchronized native void nativeHandleFlingGesture(float posX, float posY, float velocityX, float velocityY); private synchronized native void nativeHandlePinchGesture(float posX, float posY, float scale, float velocity); private synchronized native void nativeHandleRotateGesture(float posX, float posY, float rotation); private synchronized native void nativeHandleShoveGesture(float distance); private synchronized native void nativeQueueSceneUpdate(String componentPath, String value); private synchronized native void nativeApplySceneUpdates(); private synchronized native void nativePickFeature(float posX, float posY, FeaturePickListener listener); private native void nativeOnUrlSuccess(byte[] rawDataBytes, long callbackPtr); private native void nativeOnUrlFailure(long callbackPtr); native long nativeAddDataSource(String name); native void nativeRemoveDataSource(long pointer); native void nativeClearDataSource(long pointer); native void nativeAddFeature(long pointer, double[] coordinates, int[] rings, String[] properties); native void nativeAddGeoJson(long pointer, String geojson); native void nativeSetDebugFlag(int flag, boolean on); // Private members private String scenePath; private long time = System.nanoTime(); private GLSurfaceView mapView; private AssetManager assetManager; private TouchInput touchInput; private FontFileParser fontFileParser; private DisplayMetrics displayMetrics = new DisplayMetrics(); private HttpHandler httpHandler; private FeaturePickListener featurePickListener; // A static map of client data sources added dynamically. This map has static storage duration // because it should mimic the lifetime of native objects whose lifetime is the entire program. private static Map<String, MapData> clientDataSources = new HashMap<>(); // GLSurfaceView.Renderer methods @Override public void onDrawFrame(GL10 gl) { long newTime = System.nanoTime(); float delta = (newTime - time) / 1000000000.0f; time = newTime; nativeUpdate(delta); nativeRender(); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { nativeSetPixelScale(displayMetrics.density); nativeResize(width, height); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { nativeInit(this, assetManager, scenePath); // nativeInit() is safe to call twice, this invocation ensures that the jni // environment is attached to the rendering thread nativeSetupGL(); } // Networking methods void cancelUrlRequest(String url) { if (httpHandler == null) { return; } httpHandler.onCancel(url); } boolean startUrlRequest(String url, final long callbackPtr) throws Exception { if (httpHandler == null) { return false; } httpHandler.onRequest(url, new Callback() { @Override public void onFailure(Request request, IOException e) { nativeOnUrlFailure(callbackPtr); //e.printStackTrace(); } @Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { nativeOnUrlFailure(callbackPtr); throw new IOException("Unexpected response code: " + response); } BufferedSource source = response.body().source(); byte[] bytes = source.readByteArray(); nativeOnUrlSuccess(bytes, callbackPtr); } }); return true; } // Font Fetching String getFontFilePath(String key) { return fontFileParser.getFontFile(key); } public String getFontFallbackFilePath(int importance, int weightHint) { return fontFileParser.getFontFallback(importance, weightHint); } }
package org.intermine.xml.full; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.util.StringUtil; import org.intermine.util.XmlUtil; /** * Representation of an object * @author Andrew Varley * @author Kim Rutherford */ public class Item implements Comparable { private String identifier = ""; private String className = ""; private String implementations = ""; private Map<String, Attribute> attributes = new HashMap<String, Attribute>(); private Map<String, Reference> references = new HashMap(); private Map<String, ReferenceList> collections = new HashMap(); private Model model = null; private ClassDescriptor classDescriptor = null; private Set implementationClassDescriptors = null; /** * Construct an item. */ protected Item() { // nothing to do } /** * Construct an item. * @see ItemFactory * @param model the Model used to type-check set methods; if null no type checking is done * @param identifier item identifier * @param className name of described class * @param implementations names of implemented classes */ protected Item(Model model, String identifier, String className, String implementations) { this.identifier = identifier; this.className = className; this.implementations = implementations; setModel(model); } /** * Construct an item withno Model. The calls to the set methods won't be type checked unless * setModel() is called. * @see ItemFactory * @param identifier item identifier * @param className name of described class * @param implementations names of implemented classes */ protected Item(String identifier, String className, String implementations) { this(null, identifier, className, implementations); } /** * Set the Model to use when checking calls to the other set methods * @param model the Model */ public void setModel(Model model) { this.model = model; implementationClassDescriptors = null; setClassDescriptor(className); } /** * Return the model that was passed to the constructor or set with setModel(). * @return the Model */ public Model getModel() { return model; } /** * Set the identifier of this item * @param identifier the identifier */ public void setIdentifier(String identifier) { this.identifier = identifier; } /** * Get the identifier of this item * @return the identifier */ public String getIdentifier() { return identifier; } /** * Set the class of this item * @param className the class */ public void setClassName(String className) { if (className == null) { throw new IllegalArgumentException("className argument cannot be null"); } classDescriptor = getClassDescriptorByName(className); this.className = className; } /** * Get the class name of this item * @return the class name */ public String getClassName() { return className; } /** * Set the "implements" of this item * @param implementations the interfaces that this item implements */ public void setImplementations(String implementations) { if (implementations == null) { throw new IllegalArgumentException("implementations argument cannot be null"); } implementationClassDescriptors = null; checkImplementations(implementations); this.implementations = implementations; } /** * Get the interfaces implemented by this item * @return the implemented interfaces */ public String getImplementations() { return implementations; } /** * Add an attribute * @param attribute the Attribute to add */ public void addAttribute(Attribute attribute) { String name = attribute.getName(); if (!checkAttribute(name)) { throw new RuntimeException("class \"" + className + "\" has no \"" + name + "\" attribute"); } if (attribute.getValue() == null) { throw new RuntimeException("value cannot be null for attribute " + className + "." + name); } if (attribute.getValue().equals("")) { throw new RuntimeException("value cannot be an empty string for attribute " + className + "." + name); } attributes.put(name, attribute); } /** * Remove a attribute of the specified name if it exists * @param attributeName name of the attribute to remove */ public void removeAttribute(String attributeName) { if (!checkAttribute(attributeName)) { throw new RuntimeException("class \"" + className + "\" has no \"" + attributeName + "\" attribute"); } attributes.remove(attributeName); } /** * Get all the attributes * @return all the attributes */ public Collection<Attribute> getAttributes() { return attributes.values(); } /** * Get a named attribute * @param attributeName the attribute name * @return the Attribute with the given name */ public Attribute getAttribute(String attributeName) { if (!checkAttribute(attributeName)) { throw new RuntimeException("class \"" + classDescriptor.getName() + "\" has no \"" + attributeName + "\" attribute"); } return attributes.get(attributeName); } /** * Return true if named attribute exists * @param attributeName the attribute name * @return true if the attribute exists */ public boolean hasAttribute(String attributeName) { //checkAttribute(attributeName); return attributes.containsKey(attributeName); } /** * Add a reference * @param reference the reference to add */ public void addReference(Reference reference) { checkReference(reference.getName()); references.put(reference.getName(), reference); } /** * Remove a reference of the specified name if it exists * @param referenceName name of the reference to remove */ public void removeReference(String referenceName) { checkReference(referenceName); references.remove(referenceName); } /** * Get all the references * @return all the references */ public Collection getReferences() { return references.values(); } /** * Get a named reference * @param referenceName the reference name * @return the Reference with the given name */ public Reference getReference(String referenceName) { checkReference(referenceName); return references.get(referenceName); } /** * Return true if named reference exists * @param referenceName the reference name * @return true if the reference exists */ public boolean hasReference(String referenceName) { checkReference(referenceName); return references.containsKey(referenceName); } /** * Add a collection * @param collection the collection to add */ public void addCollection(ReferenceList collection) { checkCollection(collection.getName()); collections.put(collection.getName(), collection); } /** * Remove a collection of the specified name if it exists * @param collectionName name of the collection to remove */ public void removeCollection(String collectionName) { checkCollection(collectionName); collections.remove(collectionName); } /** * Get all the collections * @return all the collections */ public Collection getCollections() { return collections.values(); } /** * Return true if named collection exists * @param collectionName the collection name * @return true if the collection exists */ public boolean hasCollection(String collectionName) { checkCollection(collectionName); return collections.containsKey(collectionName); } /** * Get a named collection * @param collectionName the collection name * @return the Collection with the given name */ public ReferenceList getCollection(String collectionName) { checkCollection(collectionName); return collections.get(collectionName); } /** * Set a colletion. * @param collectionName collection name * @param refIds ids to reference */ public void setCollection(String collectionName, List<String> refIds) { addCollection(new ReferenceList(collectionName, refIds)); } /** * Add an attribute to this item * @param name the name of the attribute * @param value the value of the attribute - cannot be null or empty */ public void setAttribute(String name, String value) { if (value == null) { throw new RuntimeException("value cannot be null for attribute " + className + "." + name); } if (value.equals("")) { throw new RuntimeException("value cannot be an empty string for attribute " + className + "." + name); } addAttribute(new Attribute(name, value)); } /** * Add an attribute to this item and set it to the empty string * @param name the name of the attribute */ public void setAttributeToEmptyString(String name) { attributes.put(name, new Attribute(name, "")); } /** * Add a reference to this item * @param name the name of the attribute * @param refId the value of the attribute */ public void setReference(String name, String refId) { if (refId.equals("")) { throw new RuntimeException("empty string used as ref_id for: " + name); } addReference(new Reference(name, refId)); } /** * Add a reference that points to a particular item. * @param name the name of the attribute * @param item the item to refer to */ public void setReference(String name, Item item) { addReference(new Reference(name, item.getIdentifier())); } /** * Add the identifier of the given Item to a collection * @param name the name of the collection * @param item the item whose identifier is to be added to the collection */ public void addToCollection(String name, Item item) { ReferenceList list = getCollection(name); if (list == null) { list = new ReferenceList(name); addCollection(list); } list.addRefId(item.getIdentifier()); } /** * Add a reference to a collection of this item * @param name the name of the collection * @param identifier the item to add to the collection */ public void addToCollection(String name, String identifier) { if (identifier.equals("")) { throw new RuntimeException("empty string added to collection for: " + name); } ReferenceList list = getCollection(name); if (list == null) { list = new ReferenceList(name); addCollection(list); } list.addRefId(identifier); } /** * Return true if the name parameter is an attribute of the class for this Item or if * the Model or the className of this Item haven't been set. * @param name the attribute name * @return true if the name is a valid attribute name */ public boolean checkAttribute(String name) { if (model == null || classDescriptor == null) { return true; } Iterator cdIter = getAllClassDescriptors().iterator(); while (cdIter.hasNext()) { ClassDescriptor cd = (ClassDescriptor) cdIter.next(); if (cd.getAttributeDescriptorByName(name, true) != null) { return true; } } return false; } /** * Throw a RuntimeException if the name parameter isn't an reference in the class set by * setClassName() in the Model set by setModel(). Returns immediately if the Model or the * className of this Item haven't been set. * @param name the reference name * */ protected void checkReference(String name) { if (model == null || classDescriptor == null) { return; } if (!canHaveReference(name)) { throw new RuntimeException("class \"" + classDescriptor.getName() + "\" has no \"" + name + "\" reference"); } } /** * Return true if and only if the argument names a possible reference for this Item. ie. the * ClassDescriptor for this Item contains a ReferenceDescriptor for this name. * @param name the field name * @return Return true if and only if this Item has a reference of the given name in the model */ public boolean canHaveReference(String name) { return classDescriptor.getReferenceDescriptorByName(name, true) != null; } /** * Return true if and only if the argument names a possible collection for this Item. ie. the * ClassDescriptor for this Item contains a CollectionDescriptor for this name. * @param name the field name * @return Return true if and only if this Item has a collection of the given name in the model */ public boolean canHaveCollection(String name) { return classDescriptor.getCollectionDescriptorByName(name, true) != null; } /** * Throw a RuntimeException if the name parameter isn't an collection in the class set by * setClassName() in the Model set by setModel(). Returns immediately if the Model or the * className of this Item haven't been set. * @param name the collection name */ protected void checkCollection(String name) { if (model == null || classDescriptor == null) { return; } if (classDescriptor.getCollectionDescriptorByName(name, true) == null) { throw new RuntimeException("class \"" + classDescriptor.getName() + "\" has no \"" + name + "\" collection"); } } /** * Throw RuntimeException if the given implementations don't match the model. * @param implementations the interfaces that this item implements */ protected void checkImplementations(String implementations) { if (model == null) { return; } getImplementClassDescriptors(implementations); } /** * Throw a RuntimeException if any of the named class isn't in the Model set by setModel(). * Returns null if the model isn't set or className is "". * @param className the class name * @return the ClassDescriptor for the given class */ protected ClassDescriptor getClassDescriptorByName(String className) { if (model == null) { return null; } if (className.equals("")) { return null; } String classNameNS = XmlUtil.getNamespaceFromURI(className); if (!model.getNameSpace().toString().equals(classNameNS)) { throw new RuntimeException("class \"" + className + "\" is not in the Model " + "(namespace doesn't match \"" + model.getNameSpace() + "\" != \"" + classNameNS + "\")"); } String fullClassName = model.getPackageName() + "." + XmlUtil.getFragmentFromURI(className); ClassDescriptor cd = model.getClassDescriptorByName(fullClassName); if (cd == null) { throw new IllegalArgumentException("class \"" + fullClassName + "\" is not in the Model"); } return cd; } /** * Set the classDescriptor attribute to be the ClassDescriptor for the given className in the * Model set by setModel(). Returns immediately if the Model hasn't been set or the className * parameter is "". * @param className the class name */ protected void setClassDescriptor(String className) { if (model != null && !className.equals("")) { String fullClassName = model.getPackageName() + "." + XmlUtil.getFragmentFromURI(className); classDescriptor = getClassDescriptorByName(fullClassName); } } /** * Return the ClassDescriptors of the class of this Item (as given by className) and all the * implementations. Call only if model, className and implementations are set. * @return all the ClassDescriptors for this Item */ protected Set getAllClassDescriptors() { Set cds = new HashSet(); Set implementationCds = getImplementClassDescriptors(implementations); if (implementationCds != null) { cds.addAll(implementationCds); } cds.add(classDescriptor); return cds; } /** * Returns the ClassDescriptors for the given implementations. Returns null if the Model hasn't * been set. Throw a RuntimeException if any of the classes named in the implementations * parameter aren't in the Model. * @param implementations the interfaces that this item implements * @return the ClassDescriptors for the given implementations. Returns null if the Model hasn't * been set */ protected Set getImplementClassDescriptors(String implementations) { if (implementations.length() == 0) { return null; } if (implementationClassDescriptors != null) { return implementationClassDescriptors; } Set cds = new HashSet(); String [] bits = StringUtil.split(implementations, " "); for (int i = 0; i < bits.length; i++) { ClassDescriptor cd = getClassDescriptorByName(bits[i]); cds.add(cd); } implementationClassDescriptors = cds; return implementationClassDescriptors; } /** * {@inheritDoc} */ public boolean equals(Object o) { if (o instanceof Item) { Item i = (Item) o; return identifier.equals(i.identifier) && className.equals(i.className) && implementations.equals(i.implementations) && attributes.equals(i.attributes) && references.equals(i.references) && collections.equals(i.collections); } return false; } /** * Compare items first by class, then by identifier, intended for creating * ordered output files. * {@inheritDoc} */ public int compareTo(Object o) { if (!(o instanceof Item)) { throw new RuntimeException("Attempt to compare an item to a " + o.getClass() + " (" + o.toString() + ")"); } Item i = (Item) o; int compValue = this.getClassName().compareTo(i.getClassName()); if (compValue == 0) { compValue = this.getIdentifier().compareTo(i.getIdentifier()); } return compValue; } /** * {@inheritDoc} */ public int hashCode() { return identifier.hashCode() + 3 * className.hashCode() + 5 * implementations.hashCode() + 7 * attributes.hashCode() + 11 * references.hashCode() + 13 * collections.hashCode(); } /** * {@inheritDoc} */ public String toString() { return XmlUtil.indentXmlSimple(FullRenderer.render(this)); } }
package de.uni.freiburg.iig.telematik.swat.analysis.gui; import de.invation.code.toval.misc.wd.ProjectComponentException; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.Locale; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import org.processmining.analysis.sciffchecker.logic.reasoning.CheckerReport; import de.uni.freiburg.iig.telematik.swat.analysis.Analysis; import de.uni.freiburg.iig.telematik.swat.analysis.AnalysisController; import de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.ModelCheckerResult; import de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.sciff.presenter.SciffResultPresenter; import de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.sciff.presenter.SciffResultPresenter.resultType; import de.uni.freiburg.iig.telematik.swat.analysis.prism.PrismFunctionValidator; import de.uni.freiburg.iig.telematik.swat.patterns.logic.patterns.CompliancePattern; import de.uni.freiburg.iig.telematik.swat.workbench.components.SwatComponentType; import de.uni.freiburg.iig.telematik.swat.workbench.components.SwatComponents; import de.uni.freiburg.iig.telematik.swat.workbench.Workbench; import de.uni.freiburg.iig.telematik.swat.workbench.dialog.AnalysisHashErrorDialog; import de.uni.freiburg.iig.telematik.swat.workbench.exception.SwatComponentException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** Panel on right side of SWAT. Shows analysis results **/ public class AnalyzePanel extends JPanel implements ItemListener { private static final long serialVersionUID = 1L; /*private JPanel mButtonPanel; private JButton mEditButton; private JButton mRunButton; private JButton mSaveButton;*/ private AnalysisController mAnalysisController; private JComboBox dropDown; public AnalyzePanel(AnalysisController analysisController) throws Exception { mAnalysisController = analysisController; updatePatternResults(); } private String getDateShort() { Date today = new Date(); DateFormat formatter = DateFormat.getDateInstance( DateFormat.SHORT, new Locale(System.getProperty("user.language"), System .getProperty("user.country"))); return formatter.format(today); } public void updatePatternResults() throws Exception { this.removeAll(); JPanel content = new JPanel(new GridBagLayout()); JLabel analysisName = new JLabel("Analysis from " + getDateShort()); JButton editButton = new JButton("Edit"); JButton runButton = new JButton("Run"); JButton saveButton = new JButton("Save"); JPanel propertyPanel = new JPanel(); propertyPanel.setLayout(new BoxLayout(propertyPanel, BoxLayout.Y_AXIS)); Box box = Box.createVerticalBox(); box.add(getAnalysisDropDown(Workbench.getInstance().getNameOfCurrentComponent())); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); buttonPanel.add(editButton); buttonPanel.add(runButton); buttonPanel.add(saveButton); box.add(jPanelLeft(analysisName)); box.add(buttonPanel); box.add(jPanelLeft(new JLabel("Patterns to Check: "))); JPanel northPanel = new JPanel(new BorderLayout()); northPanel.add(propertyPanel, BorderLayout.NORTH); JScrollPane jsp = new JScrollPane(northPanel); // TODO make height dynamic, when the whole window is resized jsp.setPreferredSize(new Dimension(50, 550)); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); jsp.setVisible(true); content.setLayout(new BorderLayout()); content.add(box, BorderLayout.NORTH); content.add(jsp, BorderLayout.CENTER); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { mAnalysisController.openPatternDialog(); } }); runButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { invokeModelChecking(); } catch (Exception e) { Workbench.errorMessage("Analysis Exception while running model checker: " + e.getMessage(), e, true); } } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { saveRules(); } catch (Exception ex) { Workbench.errorMessage("Cold not store analysis ", ex, true); Logger.getLogger(AnalyzePanel.class.getName()).log(Level.SEVERE, null, ex); } } }); ArrayList<CompliancePattern> patterns = mAnalysisController.getPatterns(); for (CompliancePattern pattern : patterns) { if (pattern.isInstantiated()) { propertyPanel.add(new PatternResultPanel(pattern)); } } this.add(content); addModelCheckerResult(); } /** start the model checking with SCIFF or PRISM **/ private void invokeModelChecking() throws Exception { if (Workbench.getInstance().getTypeOfCurrentComponent().equals(SwatComponentType.PETRI_NET)) { if (!PrismFunctionValidator.checkPrism()) Workbench.errorMessage("PRISM is not correctly set-up", new Exception("Could not load Prism"), true); //return; } mAnalysisController.runModelChecker(); } private Component getAnalysisDropDown(String netID) throws ProjectComponentException { if (dropDown == null) { Collection<Analysis> analyses = getAvailableAnalyses(netID); Collections.sort((List) analyses); dropDown = new JComboBox(); dropDown.addItem("New Analysis..."); for (Analysis a : analyses) dropDown.addItem(a); dropDown.addItemListener(this); } return dropDown; } private Collection<Analysis>getAvailableAnalyses(String netID) throws ProjectComponentException{ LinkedList<Analysis> result = new LinkedList<>(); SwatComponents sc=SwatComponents.getInstance(); try{ result.addAll(sc.getContainerPetriNets().getContainerAnalysis(netID).getComponents()); } catch (ProjectComponentException e){} try{ result.addAll(sc.getContainerAristaflowLogs().getContainerAnalysis(netID).getComponents()); } catch (ProjectComponentException e){} try { result.addAll(sc.getContainerMXMLLogs().getContainerAnalysis(netID).getComponents()); } catch (ProjectComponentException e){} try{ result.addAll(sc.getContainerXESLogs().getContainerAnalysis(netID).getComponents()); } catch (ProjectComponentException e){} return result; } private JPanel jPanelLeft(JComponent k) { JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT)); p.add(k); return p; } @SuppressWarnings("rawtypes") private void saveRules() throws Exception { SwatComponents sc = SwatComponents.getInstance(); String analysisTargetName = Workbench.getInstance().getNameOfCurrentComponent(); try { String name = JOptionPane.showInputDialog(this, "Please name analysis", dropDown.getSelectedItem().toString()); String oldName = getSelectedDropDownItemName(); if (name.equalsIgnoreCase(oldName)) { dropDown.removeItemAt(dropDown.getSelectedIndex()); sc.getContainerPetriNets().getContainerAnalysis(oldName).removeComponent(oldName, true); } Analysis save = new Analysis(name, mAnalysisController.getPatterns()); save.setHashCode(Workbench.getInstance().getHashOfCurrentComponent()); save.setLoadedFromDisk(); storeAnalysis(analysisTargetName, save); dropDown.addItem(save); dropDown.setSelectedItem(save); } catch (SwatComponentException e) { Workbench.errorMessage("Could process analysis", e, true); } } public void setPatterns(Analysis analysis) throws Exception{ mAnalysisController.setPatterns(analysis.getPatternSetting()); updatePatternResults(); updateUI(); } @Override /**Listen to dropdown change**/ public void itemStateChanged(ItemEvent e) { if (dropDown.getSelectedItem() instanceof Analysis) { try { Analysis a = (Analysis) dropDown.getSelectedItem(); System.out.println("Setting pattern..."); setPatterns(a); if (a.getHashCode() != Workbench.getInstance().getHashOfCurrentComponent()) { boolean recompute = new AnalysisHashErrorDialog(Workbench.getInstance().getTypeOfCurrentComponent()).showUpdateDialog(); if (recompute) { try { invokeModelChecking(); } catch (Exception e1) { Workbench.errorMessage("Could not invoke model checking", e1, true); } } } } catch (Exception ex) { Logger.getLogger(AnalyzePanel.class.getName()).log(Level.SEVERE, null, ex); } } } private String getSelectedDropDownItemName() { String name; if (dropDown.getSelectedItem() instanceof Analysis) name = ((Analysis) dropDown.getSelectedItem()).toString(); else name = ""; return name; } /**display examples when usign SCIFF**/ private void addModelCheckerResult() { if (ModelCheckerResult.hasAResult() && ModelCheckerResult.getResult() instanceof CheckerReport) { final CheckerReport report = (CheckerReport) ModelCheckerResult.getResult(); JButton wrong = new JButton("violating (" + report.wrongInstances().size() + ")"); JButton correct = new JButton("correct (" + report.correctInstances().size() + ")"); ActionListener present = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SciffResultPresenter presenter = new SciffResultPresenter(report); if (e.getActionCommand().contains("violating")) presenter.show(resultType.WRONG); else presenter.show(resultType.CORRECT); } }; wrong.addActionListener(present); correct.addActionListener(present); this.add(wrong); this.add(correct); //remove result out of storage ModelCheckerResult.removeResult(); } } /* public void updatePatternResults() { this.removeAll(); Box box = Box.createVerticalBox(); mButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); mEditButton = new JButton("Edit"); mRunButton = new JButton("Run"); mSaveButton = new JButton("Save"); mButtonPanel.add(mEditButton); mButtonPanel.add(mRunButton); mButtonPanel.add(mSaveButton); box.add(mButtonPanel); mEditButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { mAnalysisController.openPatternDialog(); } }); mRunButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { mAnalysisController.runModelChecker(); } }); ArrayList<CompliancePattern> patterns = mAnalysisController.getPatterns(); for (CompliancePattern pattern : patterns) { if (pattern.isInstantiated()) { box.add(new PatternResultPanel(pattern)); } } this.add(box); } */ private void storeAnalysis(String componentName, Analysis save) throws ProjectComponentException { //which kind of log SwatComponents comp = SwatComponents.getInstance(); if(comp.getContainerAristaflowLogs().containsComponent(componentName)){ comp.getContainerAristaflowLogs().addAnalysis(save, componentName, true); return; } else if (comp.getContainerMXMLLogs().containsComponent(componentName)){ comp.getContainerMXMLLogs().addAnalysis(save, componentName, true); return; } else if (comp.getContainerXESLogs().containsComponent(componentName)){ comp.getContainerXESLogs().addAnalysis(save, componentName, true); return; } else if (comp.getContainerPetriNets().containsComponent(componentName)){ comp.getContainerPetriNets().addAnalysis(save, componentName, true); return; } throw new ProjectComponentException("Could not store analysis for "+componentName+": Could not find component"); } }
package dr.app.beagle.evomodel.parsers; import dr.xml.*; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.app.beagle.evomodel.substmodel.EmpiricalAminoAcidModel; import dr.evomodel.substmodel.*; /** * BEAGLE parser for empirical amino acid models */ public class EmpiricalAminoAcidModelParser extends AbstractXMLObjectParser { public static final String EMPIRICAL_AMINO_ACID_MODEL = "aminoAcidModel"; public static final String FREQUENCIES = "frequencies"; public static final String TYPE = "type"; public String getParserName() { return EMPIRICAL_AMINO_ACID_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { FrequencyModel freqModel = null; if (xo.hasAttribute(FREQUENCIES)) { XMLObject cxo = xo.getChild(FREQUENCIES); freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class); } EmpiricalRateMatrix rateMatrix = null; String type = xo.getStringAttribute(TYPE); if (type.equals(AminoAcidModelType.BLOSUM_62.getXMLName())) { rateMatrix = Blosum62.INSTANCE; } else if (type.equals(AminoAcidModelType.DAYHOFF.getXMLName())) { rateMatrix = Dayhoff.INSTANCE; } else if (type.equals(AminoAcidModelType.JTT.getXMLName())) { rateMatrix = JTT.INSTANCE; } else if (type.equals(AminoAcidModelType.MT_REV_24.getXMLName())) { rateMatrix = MTREV.INSTANCE; } else if (type.equals(AminoAcidModelType.CP_REV_45.getXMLName())) { rateMatrix = CPREV.INSTANCE; } else if (type.equals(AminoAcidModelType.WAG.getXMLName())) { rateMatrix = WAG.INSTANCE; } else if (type.equals(AminoAcidModelType.FLU.getXMLName())) { rateMatrix = WAG.INSTANCE; } else { throw new XMLParseException("Unrecognized empirical amino acid model: " + type); } return new EmpiricalAminoAcidModel(rateMatrix, freqModel); }
package org.voltdb.importclient.kafka10; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import org.apache.kafka.clients.consumer.CommitFailedException; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.PartitionInfo; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.WakeupException; import org.voltcore.logging.Level; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.EstTime; import org.voltdb.client.ProcedureCallback; import org.voltdb.importclient.kafka.util.DurableTracker; import org.voltdb.importclient.kafka.util.KafkaCommitPolicy; import org.voltdb.importclient.kafka.util.KafkaConstants; import org.voltdb.importclient.kafka.util.KafkaUtils; import org.voltdb.importclient.kafka.util.PendingWorkTracker; import org.voltdb.importclient.kafka.util.ProcedureInvocationCallback; import org.voltdb.importclient.kafka.util.SimpleTracker; import org.voltdb.importer.CommitTracker; import org.voltdb.importer.ImporterLifecycle; import org.voltdb.importer.formatter.FormatException; import org.voltdb.importer.formatter.Formatter; import org.voltdb.importer.formatter.FormatterBuilder; import au.com.bytecode.opencsv_voltpatches.CSVParser; public abstract class KafkaConsumerRunner implements Runnable { private static final VoltLogger LOGGER = new VoltLogger("KAFKAIMPORTER"); protected Consumer<ByteBuffer, ByteBuffer> m_consumer; protected final KafkaStreamImporterConfig m_config; protected final ImporterLifecycle m_lifecycle; private final AtomicReference<Map<TopicPartition, AtomicLong>> m_lastCommittedOffSets = new AtomicReference<>(); private final AtomicReference<Map<TopicPartition, CommitTracker>> m_trackerMap = new AtomicReference<>(); private final Map<TopicPartition, AtomicLong> m_lastSeekedOffSets = new ConcurrentHashMap<>(); private final Map<TopicPartition, AtomicLong> m_pauseOffsets = new ConcurrentHashMap<>(); private final Map<TopicPartition, PendingWorkTracker> m_workTrackers = new ConcurrentHashMap<>(); protected final AtomicBoolean m_done = new AtomicBoolean(false); //Formatter by topic and partition. private final Map<String, Formatter> m_formatters = new HashMap<>(); //for commit policies. private long m_lastCommitTime = 0; private final int m_waitSleepMs = 10; private final ReentrantLock m_offsetLock = new ReentrantLock(); public KafkaConsumerRunner(ImporterLifecycle lifecycle, KafkaStreamImporterConfig config, Consumer<ByteBuffer, ByteBuffer> consumer) throws Exception { m_lifecycle = lifecycle; m_consumer = consumer; m_config = config; m_lastCommittedOffSets.set(new HashMap<>()); m_trackerMap.set(new HashMap<>()); } protected void subscribe() { m_consumer.subscribe(Arrays.asList(m_config.getTopics().split(",")), new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { if (partitions.isEmpty()) { return; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Consumer group " + m_config.getGroupId() + " drops topic/partitions:" + partitions); } //This method is called before a rebalance operation starts and after the consumer stops fetching data. //So commit offsets for the partitions before they are revoked commitOffsets(partitions.stream().collect(Collectors.toList())); Map<TopicPartition, CommitTracker> trackers = new HashMap<>(); trackers.putAll(m_trackerMap.get()); Map<TopicPartition, AtomicLong> lastCommittedOffSets = new HashMap<>(); lastCommittedOffSets.putAll(m_lastCommittedOffSets.get()); for (TopicPartition partition : partitions) { trackers.remove(partition); lastCommittedOffSets.remove(partition); m_pauseOffsets.remove(partition); m_workTrackers.remove(partition); } m_trackerMap.set(trackers); m_lastCommittedOffSets.set(lastCommittedOffSets); } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Consumer group " + m_config.getGroupId() + " is assigned with topic/partition" + partitions); } } }); } //add trackers for new topic-partition in this importer private void calculateTrackers(Collection<TopicPartition> partitions) { Map<TopicPartition, CommitTracker> trackers = new HashMap<>(); trackers.putAll(m_trackerMap.get()); Map<TopicPartition, AtomicLong> lastCommittedOffSets = new HashMap<>(); lastCommittedOffSets.putAll(m_lastCommittedOffSets.get()); boolean newTopicPartition = false; for (TopicPartition partition : partitions) { if (m_trackerMap.get().get(partition) != null) { continue; } newTopicPartition = true; long startOffset = -1L; CommitTracker commitTracker = null; if (m_config.getCommitPolicy() == KafkaCommitPolicy.TIME && m_config.getTriggerValue() > 0) { commitTracker = new SimpleTracker(); } else { commitTracker = new DurableTracker(KafkaConstants.IMPORT_GAP_LEAD, partition.topic(), partition.partition(), m_config.getGroupId()); } trackers.put(partition, commitTracker); try { OffsetAndMetadata offsetAndMetaData = m_consumer.committed(partition); startOffset = offsetAndMetaData != null ? offsetAndMetaData.offset() : -1L; if (startOffset > -1L) { commitTracker.resetTo(startOffset); } } catch (WakeupException we) { if (m_done.get()) { return; } } catch (KafkaException e) { if (m_done.get()) { LOGGER.info("Failed to read committed offsets for group " + m_config.getGroupId() + partition + " " + e); } else { LOGGER.error("Failed to read committed offsets for group " + m_config.getGroupId() + partition, e); } } lastCommittedOffSets.put(partition, new AtomicLong(startOffset)); m_pauseOffsets.put(partition, new AtomicLong(-1)); m_workTrackers.put(partition, new PendingWorkTracker()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting offset for group:" + m_config.getGroupId() + ":" + startOffset + " partition:" + partition); } } if (newTopicPartition) { m_trackerMap.set(trackers); m_lastCommittedOffSets.set(lastCommittedOffSets); } } protected void shutdown() { if (m_consumer == null) { return; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Shutdown Kafka consumer for group " + m_config.getGroupId()); } m_done.set(true); try { m_consumer.wakeup(); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Kafka wakeup interruption while cleaning up Kafka consumer:" + e.getMessage()); } } } public abstract boolean invoke(String rawMessage, long offset, String topic, Object[] params, ProcedureCallback procedureCallback) throws Exception; @Override public void run() { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting Kafka consumer for group:" + m_config.getGroupId() + " topics:" + m_config.getTopics()); } List<TopicPartition> seekList = new ArrayList<>(); Map<TopicPartition, AtomicLong> submitCounts = new HashMap<>(); CSVParser csvParser = new CSVParser(); try { subscribe(); int sleepCounter = 1; while (m_lifecycle.shouldRun()) { try { seek(seekList); seekList.clear(); //The consumer will poll messages from earliest or the committed offset on the first polling. //The messages in next poll starts at the largest offset + 1 in the previous polled messages. //Every message is polled only once. ConsumerRecords<ByteBuffer, ByteBuffer> records = null; if (!m_lifecycle.shouldRun()) { break; } try { records = m_consumer.poll(m_config.getPollTimeout()); } catch (WakeupException we) { if (m_done.get()) { break; } } catch (Throwable t) { if (m_done.get()) { break; } LOGGER.warn("Errors seen when polling data from Kafka:" + t.getMessage()); } if (records == null || records.isEmpty()) { List<TopicPartition> topicPartitions = m_lastCommittedOffSets.get().keySet().stream().collect(Collectors.toList()); commitOffsets(topicPartitions); try { Thread.sleep(m_waitSleepMs);} catch (InterruptedException ie) {} continue; } calculateTrackers(records.partitions()); List<TopicPartition> topicPartitions = new ArrayList<>(); for (TopicPartition partition : records.partitions()) { if (!m_lifecycle.shouldRun()) { break; } Formatter formatter = getFormatter(partition.topic()); int partitionSubmittedCount = 0; CommitTracker commitTracker = getCommitTracker(partition); AtomicLong lastCommittedOffset = m_lastCommittedOffSets.get().get(partition); //partition revoked? if (commitTracker == null || lastCommittedOffset == null) { continue; } AtomicLong submitCount = submitCounts.get(partition); if (submitCount == null) { submitCount = new AtomicLong(0); submitCounts.put(partition, submitCount); } String topicIdentifer = "group " + m_config.getGroupId() + "-" + partition; List<ConsumerRecord<ByteBuffer, ByteBuffer>> messages = records.records(partition); int count = messages.size(); for (int i = 0; i < count; i++) { if (!m_lifecycle.shouldRun()) { break; } ConsumerRecord<ByteBuffer, ByteBuffer> record = messages.get(i); long offset = record.offset(); //Poll the partition next round after moving the position to the last committed offset if (lastCommittedOffset.longValue() > -1L && offset < lastCommittedOffset.longValue()) { seekList.add(partition); break; } //The Kafka message offsets are consecutive numbers. Kafka messages come in ascending order by the offsets //A message record in Kafka 10, not as Kafka 8, does not have the offset of next message. //Thus get next offset from next message for the purpose of tracking. The next offset for the last message in the batch // will be the offset of the message + 1. long nextOffSet = offset + 1; if (i != (count -1)) { nextOffSet = messages.get(i + 1).offset(); } Object params[] = null; String smsg = null; try { smsg = new String(record.value().array(), StandardCharsets.UTF_8); if (formatter != null) { params = formatter.transform(ByteBuffer.wrap(smsg.getBytes())); } else { params = csvParser.parseLine(smsg); } commitTracker.submit(nextOffSet); submitCount.incrementAndGet(); ProcedureCallback cb = new ProcedureInvocationCallback(offset, nextOffSet, m_workTrackers.get(partition), commitTracker, m_done, m_pauseOffsets.get(partition), topicIdentifer); partitionSubmittedCount++; if (invoke(smsg, offset, partition.topic(), params, cb)) { m_workTrackers.get(partition).produceWork(); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Failed to process. possibly bad data: " + Arrays.toString(params)); } commitTracker.commit(nextOffSet); } } catch (FormatException | IOException e) { partitionSubmittedCount++; LOGGER.rateLimitedLog(KafkaConstants.LOG_SUPPRESSION_INTERVAL_SECONDS, Level.WARN, e, "Failed to tranform data: %s" , Arrays.toString(params)); commitTracker.commit(nextOffSet); } if (!m_lifecycle.shouldRun()) { break; } } if (partitionSubmittedCount > 0) { topicPartitions.add(partition); } } if (!m_lifecycle.shouldRun()) { break; } if (!topicPartitions.isEmpty() && KafkaCommitPolicy.shouldCommit(m_config.getCommitPolicy(), m_config.getTriggerValue(), m_lastCommitTime)) { commitOffsets(topicPartitions); } } catch(KafkaException ex) { LOGGER.error("Error seen when processing message " + m_config.getTopics(), ex); if (m_done.get()) { break; } sleepCounter = KafkaUtils.backoffSleep(sleepCounter); continue; } } } catch (Exception e) { LOGGER.error("Failed to start topic partition fetcher for " + m_config.getTopics(), e); } finally { try { commitPauseOffsets(); m_consumer.close(); m_consumer = null; } catch (Exception ignore) { //ignore } } m_done.set(true); if (LOGGER.isDebugEnabled()) { StringBuilder builder = new StringBuilder("Import detail for group " + m_config.getGroupId()); builder.append(" \n Submitted Counts:" + m_workTrackers); builder.append(" \n Committed Offsets: " + m_lastCommittedOffSets.get()); LOGGER.debug(builder.toString()); } } //Move offsets to correct positions for next poll private void seek(List<TopicPartition> seekList) { for (TopicPartition tp : seekList) { AtomicLong lastCommittedOffset = m_lastCommittedOffSets.get().get(tp); if (lastCommittedOffset != null && lastCommittedOffset.get() > -1L) { AtomicLong lastSeeked = m_lastSeekedOffSets.get(tp); //eliminate duplicate seek if (lastSeeked != null && lastSeeked.get() == lastCommittedOffset.get()) { continue; } m_consumer.seek(tp, lastCommittedOffset.longValue()); m_lastSeekedOffSets.put(tp, new AtomicLong(lastCommittedOffset.get())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Moves offset for group " + m_config.getGroupId() + " -" + tp + " to " + lastCommittedOffset); } } } } private CommitTracker getCommitTracker(TopicPartition partition) { return m_trackerMap.get().get(partition); } private void commitPauseOffsets() { Map<TopicPartition, OffsetAndMetadata> partitionToMetadataMap = new HashMap<>(); for (Map.Entry<TopicPartition, AtomicLong> entry : m_lastCommittedOffSets.get().entrySet()) { PendingWorkTracker workTracker = m_workTrackers.get(entry.getKey()); AtomicLong pauseOffset = m_pauseOffsets.get(entry.getKey()); if (workTracker == null || pauseOffset == null) { continue; } long pausedOffSet = pauseOffset.get(); boolean skipCommit = false; if (pausedOffSet != -1) { if (workTracker.waitForWorkToFinish() == false) { if (pauseOffset.get() < entry.getValue().get()) { LOGGER.warn("Committing paused offset even though a timeout occurred waiting for pending stored procedures to finish."); } else { LOGGER.warn("Refusing to commit paused offset because a timeout occurred waiting for pending stored procedures to finish."); skipCommit = true; } } } if (skipCommit) { continue; } CommitTracker commitTracker = getCommitTracker(entry.getKey()); if (commitTracker == null) { continue; } long safe = commitTracker.getSafe(); //nothing safe to commit if (safe < 0) { continue; } AtomicLong committedOffSet = m_lastCommittedOffSets.get().get(entry.getKey()); if (committedOffSet != null && committedOffSet.get() != pausedOffSet && (safe > committedOffSet.get() || pausedOffSet != -1)) { if (pausedOffSet != -1) { safe = Math.min(pausedOffSet, safe); } partitionToMetadataMap.put(entry.getKey(), new OffsetAndMetadata(safe)); committedOffSet.set(safe); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Consumer group " + m_config.getGroupId() + " committs offsets upon pausing."); } commit(partitionToMetadataMap); } private void commitOffsets(List<TopicPartition> topicPartitions) { m_offsetLock.lock(); try { Map<TopicPartition, OffsetAndMetadata> partitionToMetadataMap = new HashMap<>(); for (TopicPartition partition : topicPartitions) { CommitTracker commitTracker = getCommitTracker(partition); if (commitTracker != null) { long safe = commitTracker.getSafe(); //nothing safe to commit; if (safe < 0) { continue; } AtomicLong committedOffSet = m_lastCommittedOffSets.get().get(partition); if (committedOffSet != null) { long lastCommittedOffset = committedOffSet.longValue(); if (safe > lastCommittedOffset) { partitionToMetadataMap.put(partition, new OffsetAndMetadata(safe)); committedOffSet.set(safe); } } } else { LOGGER.debug("Consumner group " + m_config.getGroupId() + " does't have" + partition + " assigned any more."); } } commit(partitionToMetadataMap); } finally { m_offsetLock.unlock(); } } private void commit(Map<TopicPartition, OffsetAndMetadata> partitionToMetadataMap) { if (partitionToMetadataMap.isEmpty()) { return; } if (LOGGER.isDebugEnabled()) { StringBuilder builder = new StringBuilder("Consumer group " + m_config.getGroupId() + " committs offsets:"); for (Map.Entry<TopicPartition, OffsetAndMetadata> entry : partitionToMetadataMap.entrySet()) { builder.append(entry.getKey() + ":" + entry.getValue().offset()); } LOGGER.debug(builder.toString()); } try { m_consumer.commitSync(partitionToMetadataMap); m_lastCommitTime = EstTime.currentTimeMillis(); } catch (WakeupException e) { //committing while being shut down. retry... try { m_consumer.commitSync(partitionToMetadataMap); m_lastCommitTime = EstTime.currentTimeMillis(); } catch(KafkaException ke) { LOGGER.warn("Consumer group " + m_config.getGroupId() + " commit offsets:" + ke.getMessage()); } } catch (CommitFailedException ce) { LOGGER.warn("Consumer group " + m_config.getGroupId() + " commit offsets:" + ce.getMessage()); } } private Formatter getFormatter(String topic) { Formatter formatter = m_formatters.get(topic); if (formatter != null) { return formatter; } FormatterBuilder builder = m_config.getFormatterBuilder(topic); if (builder != null) { formatter = builder.create(); m_formatters.put(topic, formatter); return formatter; } return null; } public int getKafkaTopicPartitionCount() { int totalPartitions = 0; String[] topics = m_config.getTopics().split(","); for (String topic : topics) { int partitions = 0; while (partitions == 0) { try { List<PartitionInfo> info = m_consumer.partitionsFor(topic); if (info != null) { partitions = info.size(); } } catch (Exception e) { LOGGER.rateLimitedLog(KafkaConstants.LOG_SUPPRESSION_INTERVAL_SECONDS, Level.WARN, e, "Failed to get Kafka partition info"); } //paused or shutting down if (m_done.get()) { return -1; } } totalPartitions += partitions; } return totalPartitions; } }
package gov.nih.nci.calab.service.administration; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.SampleSOP; import gov.nih.nci.calab.domain.Source; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.administration.ContainerBean; import gov.nih.nci.calab.dto.administration.SampleBean; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.log4j.Logger; /* CVS $Id: ManageSampleService.java,v 1.23 2006-04-27 20:25:29 pansu Exp $ */ public class ManageSampleService { private static Logger logger = Logger.getLogger(ManageSampleService.class); public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj:results) { sampleSOPs.add((String)obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return auto-generated default value for sample name prefix */ public String getDefaultSampleNamePrefix() throws Exception { // TODO: Get configurable sample format string String sampleNamePrefix = "NCL-"; long seqId = 0; IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select max(sample.sampleSequenceId) from Sample sample"; List results = ida.search(hqlString); logger.debug("ManageSampleService.getSampleSequenceId(): results.size = " + results.size()); if (results.iterator().hasNext()) { Object obj = results.iterator().next(); logger.debug("ManageSampleService.getSampleSequenceId(): obj = " + obj); if (obj != null){ seqId = (Long)obj; } } logger.debug("ManageSampleService.getSampleSequenceId(): current seq id = " + seqId); } catch (Exception e) { logger.error("Problem in retrieving default sample ID prefix."); throw new RuntimeException("Problem in retrieving default sample ID prefix."); } finally { ida.close(); } return sampleNamePrefix + (seqId+1); } public Long getUserDefinedSequenceId(String userDefinedPrefix) { String newSequence = userDefinedPrefix.substring(userDefinedPrefix.lastIndexOf("-")+1); return StringUtils.convertToLong(newSequence); } /** * * @param sampleNamePrefix * @param lotId * @return sampleName from sampleName prefix and lotId */ public String getSampleName(String sampleNamePrefix, String lotId) { if (lotId.equals(CalabConstants.EMPTY)) { return sampleNamePrefix; } return sampleNamePrefix + "-" + lotId; } /** * * @return the default lot Id */ public String getDefaultLotId() { String lotId = CalabConstants.EMPTY; return lotId; } /** * Saves the sample into the database * * @throws Exception */ public void saveSample(SampleBean sample, ContainerBean[] containers) throws Exception{ // TODO fill in details to save the sample and associated containers. // check if the smaple is exist // For NCL, sampleId + lotId is unique -- in SampleBean, sampleId issampleName IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select count(*) from Sample sample where sample.name = '" + sample.getSampleName()+"'"; List results = ida.search(hqlString); if (results.iterator().hasNext()) { Object obj = results.iterator().next(); logger.debug("ManageSampleService.saveSample(): return object type = " + obj.getClass().getName() + " | object value = " + obj); // Yes, throws exception if (((Integer)obj).intValue() > 0) { throw new RuntimeException("The the same sample is already exist in the system."); } } // No, save it // Create Sample Object, save source, save sample, save storageElement, save SampleContainer, // set storageElement in sampleContainer, save sampleContainer again // Create sample object Sample doSample = new Sample(); // Front end source is a plain text, so just save the source object String sampleSourceName = sample.getSampleSource(); if (( sampleSourceName != null) && (sampleSourceName.trim().length() > 0)) { List existedSources = ida.search("from Source source where source.organizationName = '" + sample.getSampleSource() + "'"); Source source = null; if (existedSources.size() > 0){ source = (Source)existedSources.get(0); } else { source = new Source(); source.setOrganizationName(sample.getSampleSource()); ida.store(source); } // Create releationship between this source and this sample doSample.setSource(source); } doSample.setComments(sample.getGeneralComments()); doSample.setCreatedBy(sample.getSampleSubmitter()); doSample.setCreatedDate(StringUtils.convertToDate(sample.getAccessionDate(),CalabConstants.DATE_FORMAT)); doSample.setDescription(sample.getSampleDescription()); doSample.setLotDescription(sample.getLotDescription()); doSample.setLotId(sample.getLotId()); doSample.setName(sample.getSampleName()); doSample.setType(sample.getSampleType()); // TODO: ReceivedBy and Date are not in the wireframe. doSample.setReceivedBy(""); doSample.setReceivedDate(StringUtils.convertToDate(sample.getDateReceived(), CalabConstants.DATE_FORMAT)); doSample.setSampleSequenceId(getUserDefinedSequenceId(sample.getSampleNamePrefix())); doSample.setSolubility(sample.getSolubility()); doSample.setSourceSampleId(sample.getSourceSampleId()); // TODO: Fill in the sample SOP info, if sampleBean can pass the primary key...... String sopName = sample.getSampleSOP(); if ( (sopName != null) && (sopName.length() > 0)) { List existedSOP = ida.search("from SampleSOP sop where sop.name = '" + sopName + "'"); SampleSOP sop = (SampleSOP)existedSOP.get(0); doSample.setSampleSOP(sop); } //Save Sample ida.createObject(doSample); // Container list for (int i=0; i<containers.length;i++) { SampleContainer doSampleContainer = new SampleContainer(); // use Hibernate Hilo algorithm to generate the id doSampleContainer.setComments(containers[i].getContainerComments()); doSampleContainer.setConcentration(StringUtils.convertToFloat(containers[i].getConcentration())); doSampleContainer.setConcentrationUnit(containers[i].getConcentrationUnit()); if ((containers[i].getContainerType().equals(CalabConstants.OTHER))) { doSampleContainer.setContainerType((containers[i].getOtherContainerType())); } else { doSampleContainer.setContainerType((containers[i].getContainerType())); } doSampleContainer.setCreatedBy(sample.getSampleSubmitter()); doSampleContainer.setCreatedDate(StringUtils.convertToDate(sample.getAccessionDate(), CalabConstants.DATE_FORMAT)); doSampleContainer.setDiluentsSolvent(containers[i].getSolvent()); doSampleContainer.setQuantity(StringUtils.convertToFloat(containers[i].getQuantity())); doSampleContainer.setQuantityUnit(containers[i].getQuantityUnit()); doSampleContainer.setSafetyPrecaution(containers[i].getSafetyPrecaution()); doSampleContainer.setStorageCondition(containers[i].getStorageCondition()); doSampleContainer.setVolume(StringUtils.convertToFloat(containers[i].getVolume())); doSampleContainer.setVolumeUnit(containers[i].getVolumeUnit()); // TODO: set name is it suppose to be sequence number? doSampleContainer.setName(containers[i].getContainerName()); // TODO: relationship with storage need to be added too. HashSet<StorageElement> storages = new HashSet<StorageElement>(); String boxValue = containers[i].getStorageLocation().getBox(); if (( boxValue != null)&&(boxValue.trim().length()>0)) { List existedSE = ida.search("from StorageElement se where se.type = '" + CalabConstants.STORAGE_BOX + "' and se.location = '" + boxValue + "'"); StorageElement box = null; if (existedSE.size() > 0){ box = (StorageElement)existedSE.get(0); } else { box = new StorageElement(); box.setLocation(boxValue); box.setType(CalabConstants.STORAGE_BOX); ida.store(box); } // Create releationship between this source and this sample storages.add(box); } String shelfValue = containers[i].getStorageLocation().getShelf(); if ((shelfValue != null)&&(shelfValue.trim().length()>0)) { List existedSE = ida.search("from StorageElement se where se.type = '" + CalabConstants.STORAGE_SHELF + "' and se.location = '" + shelfValue + "'"); StorageElement shelf = null; if (existedSE.size() > 0){ shelf = (StorageElement)existedSE.get(0); } else { shelf = new StorageElement(); shelf.setLocation(shelfValue); shelf.setType(CalabConstants.STORAGE_SHELF); ida.store(shelf); } // Create releationship between this source and this sample storages.add(shelf); } String freezerValue = containers[i].getStorageLocation().getFreezer(); if ( (freezerValue != null)&& (freezerValue.length()>0)) { List existedSE = ida.search("from StorageElement se where se.type = '" + CalabConstants.STORAGE_FREEZER + "' and se.location = '" + freezerValue + "'"); StorageElement freezer = null; if (existedSE.size() > 0){ freezer = (StorageElement)existedSE.get(0); } else { freezer = new StorageElement(); freezer.setLocation(freezerValue); freezer.setType(CalabConstants.STORAGE_FREEZER); ida.store(freezer); } // Create releationship between this source and this sample storages.add(freezer); } String roomValue = containers[i].getStorageLocation().getRoom(); if ((roomValue != null)&&(roomValue.length()>0)) { List existedSE = ida.search("from StorageElement se where se.type = '" + CalabConstants.STORAGE_ROOM + "' and se.location = '" + roomValue + "'"); StorageElement room = null; if (existedSE.size() > 0){ room = (StorageElement)existedSE.get(0); } else { room = new StorageElement(); room.setLocation(roomValue); room.setType(CalabConstants.STORAGE_ROOM); ida.store(room); } // Create releationship between this source and this sample storages.add(room); } doSampleContainer.setSample(doSample); ida.store(doSampleContainer); System.out.println("ManageSampleService.saveSample(): same again with storage info"); doSampleContainer.setStorageElementCollection(storages); ida.store(doSampleContainer); } }catch (Exception e){ e.printStackTrace(); logger.error("Problem saving the sample."); ida.rollback(); throw new Exception (e.getMessage()); } finally { ida.close(); } } }
package org.rstudio.core.client.layout; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; import org.rstudio.core.client.Debug; import org.rstudio.core.client.HandlerRegistrations; import org.rstudio.core.client.events.EnsureHeightEvent; import org.rstudio.core.client.events.EnsureHeightHandler; import org.rstudio.core.client.events.WindowStateChangeEvent; import org.rstudio.core.client.events.WindowStateChangeHandler; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.widget.events.GlassVisibilityEvent; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.workbench.model.ClientInitState; import org.rstudio.studio.client.workbench.model.ClientState; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue; import static org.rstudio.core.client.layout.WindowState.*; /** * This class implements the minimizing/maximizing behavior between two * window frames. */ public class DualWindowLayoutPanel extends SimplePanel implements ProvidesResize, RequiresResize { private static class NormalHeight { public NormalHeight(int height, Integer containerHeight, Integer windowHeight) { height_ = height; containerHeight_ = containerHeight; windowHeight_ = windowHeight; } public int getHeight() { return height_; } public int getContainerHeight(int defaultValue) { assert defaultValue > 0; if (containerHeight_ == null) containerHeight_ = defaultValue; return containerHeight_.intValue(); } public int getWindowHeight(int defaultValue) { assert defaultValue > 0; if (windowHeight_ == null) windowHeight_ = defaultValue; return windowHeight_.intValue(); } public int getHeightScaledTo(int containerHeight) { if (containerHeight_ == null || containerHeight_.intValue() == containerHeight || containerHeight <= 0) { return height_; } double pct = (double)containerHeight / containerHeight_.intValue(); return (int)(pct * height_); } private int height_; private Integer containerHeight_; private Integer windowHeight_; } private class WindowStateChangeManager implements WindowStateChangeHandler { public WindowStateChangeManager(Session session) { session_ = session; } public void onWindowStateChange(WindowStateChangeEvent event) { switch (event.getNewState()) { case EXCLUSIVE: windowA_.transitionToState(EXCLUSIVE); windowB_.transitionToState(HIDE); layout(windowA_, windowB_, event.skipFocusChange()); break; case MAXIMIZE: windowA_.transitionToState(MAXIMIZE); windowB_.transitionToState(MINIMIZE); layout(windowA_, windowB_, event.skipFocusChange()); break; case MINIMIZE: windowA_.transitionToState(MINIMIZE); windowB_.transitionToState(MAXIMIZE); layout(windowA_, windowB_, event.skipFocusChange()); break; case NORMAL: windowA_.transitionToState(NORMAL); windowB_.transitionToState(NORMAL); layout(windowA_, windowB_, event.skipFocusChange()); break; case HIDE: windowA_.transitionToState(HIDE); windowB_.transitionToState(EXCLUSIVE); layout(windowA_, windowB_, event.skipFocusChange()); break; } // Defer this because layout changes are deferred by LayoutPanel. Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { session_.persistClientState(); } }); } private final Session session_; } private static class State extends JavaScriptObject { protected State() {} public native final boolean hasSplitterPos() /*-{ return typeof(this.splitterpos) != 'undefined'; }-*/; public native final int getSplitterPos() /*-{ return this.splitterpos; }-*/; public native final void setSplitterPos(int pos) /*-{ this.splitterpos = pos; }-*/; public native final String getTopWindowState() /*-{ return this.topwindowstate; }-*/; public native final void setTopWindowState(String state) /*-{ this.topwindowstate = state; }-*/; public native final boolean hasPanelHeight() /*-{ return typeof(this.panelheight) != 'undefined'; }-*/; public native final int getPanelHeight() /*-{ return this.panelheight; }-*/; public native final void setPanelHeight(int height) /*-{ this.panelheight = height; }-*/; public native final boolean hasWindowHeight() /*-{ return typeof(this.windowheight) != 'undefined'; }-*/; public native final int getWindowHeight() /*-{ return this.windowheight; }-*/; public native final void setWindowHeight(int height) /*-{ this.windowheight = height; }-*/; public static boolean equals(State a, State b) { if (a == null ^ b == null) return false; if (a == null) return true; if (a.hasSplitterPos() ^ b.hasSplitterPos()) return false; if (a.hasSplitterPos() && a.getSplitterPos() != b.getSplitterPos()) return false; if (a.hasPanelHeight() ^ b.hasPanelHeight()) return false; if (a.hasPanelHeight() && a.getPanelHeight() != b.getPanelHeight()) return false; if (a.hasWindowHeight() ^ b.hasWindowHeight()) return false; if (a.hasWindowHeight() && a.getWindowHeight() != b.getWindowHeight()) return false; if (a.getTopWindowState() == null ^ b.getTopWindowState() == null) return false; if (a.getTopWindowState() != null && !a.getTopWindowState().equals(b.getTopWindowState())) return false; return true; } } /** * Helper class to make the minimized/maximized state and splitter * position persist across browser sessions. */ private class WindowLayoutStateValue extends JSObjectStateValue { public WindowLayoutStateValue(ClientInitState clientState, String clientStateKeyName, WindowState topWindowDefaultState, int defaultSplitterPos) { super("windowlayoutstate", clientStateKeyName, ClientState.PROJECT_PERSISTENT, clientState, true); topWindowDefaultState_ = topWindowDefaultState; defaultSplitterPos_ = defaultSplitterPos; finishInit(clientState); } @Override protected void onInit(JsObject value) { normalHeight_ = new NormalHeight(defaultSplitterPos_, null, null); WindowState topWindowState = topWindowDefaultState_; try { if (value != null) { State state = value.cast(); if (state.hasSplitterPos()) { // This logic is a little tortured. At startup time, we don't // have the height of this panel (getOffsetHeight()) since it // isn't attached to the document yet. But if we wait until // we have the height to restore the size, then the user would // see some jumpiness in the UI. // So instead we persist both the panel height and window // height at save time, and assume that the difference between // the two will remain the same, and use the new window height // at load time to work backward to the new offset height. // That's probably not a great assumption, it would be better // to have a priori knowledge of the height of the panel. But // given the low severity of the number being slightly off, // this seems fine for the foreseeable future. if (state.hasWindowHeight() && state.hasPanelHeight() && state.getWindowHeight() != Window.getClientHeight()) { int deltaY = state.getWindowHeight() - state.getPanelHeight(); int newPanelHeight = Window.getClientHeight() - deltaY; // Use percentage value double pct = (double) state.getSplitterPos() / state.getPanelHeight(); normalHeight_ = new NormalHeight( (int)(pct * newPanelHeight), newPanelHeight, Window.getClientHeight()); } else { // Use absolute value normalHeight_ = new NormalHeight( state.getSplitterPos(), state.hasPanelHeight() ? state.getPanelHeight() : null, state.hasWindowHeight() ? state.getWindowHeight() : null); } } if (state.getTopWindowState() != null) topWindowState = WindowState.valueOf(state.getTopWindowState()); lastKnownValue_ = state; } } catch (Exception e) { Debug.log("Error restoring dual window state: " + e.toString()); } windowA_.onWindowStateChange( new WindowStateChangeEvent(topWindowState)); } @Override protected JsObject getValue() { NormalHeight currentHeight = normalHeight_; if (layout_.isSplitterVisible()) { currentHeight = new NormalHeight(layout_.getSplitterBottom(), layout_.getOffsetHeight(), Window.getClientHeight()); } State state = JsObject.createJsObject().cast(); state.setSplitterPos(currentHeight.getHeight()); state.setTopWindowState(windowA_.getState().toString()); state.setPanelHeight(currentHeight.getContainerHeight(getOffsetHeight())); state.setWindowHeight(currentHeight.getWindowHeight(Window.getClientHeight())); return state.cast(); } @Override protected boolean hasChanged() { State state = getValue().cast(); if (state.getSplitterPos() > state.getPanelHeight() || state.getSplitterPos() < 0) { Debug.log("Invalid splitter position detected: " + state.getSplitterPos() + "/" + state.getPanelHeight()); return false; } if (!State.equals(lastKnownValue_, state)) { lastKnownValue_ = state; return true; } return false; } private State lastKnownValue_; private final WindowState topWindowDefaultState_; private final int defaultSplitterPos_; } public DualWindowLayoutPanel(final EventBus eventBus, final LogicalWindow windowA, final LogicalWindow windowB, Session session, String clientStateKeyName, final WindowState topWindowDefaultState, final int defaultSplitterPos) { windowA_ = windowA; windowB_ = windowB; session_ = session; setSize("100%", "100%"); layout_ = new BinarySplitLayoutPanel(new Widget[] { windowA.getNormal(), windowA.getMinimized(), windowB.getNormal(), windowB.getMinimized()}, 3); layout_.setSize("100%", "100%"); topWindowStateChangeManager_ = new WindowStateChangeManager(session); bottomWindowStateChangeManager_ = new WindowStateChangeHandler() { public void onWindowStateChange(WindowStateChangeEvent event) { WindowState topState; switch (event.getNewState()) { case NORMAL: topState = NORMAL; break; case MAXIMIZE: topState = MINIMIZE; break; case MINIMIZE: topState = MAXIMIZE; break; case HIDE: topState = EXCLUSIVE; break; case EXCLUSIVE: topState = HIDE; break; default: throw new IllegalArgumentException( "Unknown WindowState " + event.getNewState()); } windowA_.onWindowStateChange( new WindowStateChangeEvent(topState)); } }; hookEvents(); new WindowLayoutStateValue(session.getSessionInfo().getClientState(), clientStateKeyName, topWindowDefaultState, defaultSplitterPos); setWidget(layout_); if (eventBus != null) { layout_.addSplitterBeforeResizeHandler(new SplitterBeforeResizeHandler() { public void onSplitterBeforeResize(SplitterBeforeResizeEvent event) { // If the splitter ends up causing a minimize operation, then // we'll need to have saved the normal height for when the // user decides to restore the panel. snapMinimizeNormalHeight_ = new NormalHeight( layout_.getSplitterBottom(), layout_.getOffsetHeight(), Window.getClientHeight()); eventBus.fireEvent(new GlassVisibilityEvent(true)); } }); layout_.addSplitterResizedHandler(new SplitterResizedHandler() { public void onSplitterResized(SplitterResizedEvent event) { WindowState topState = resizePanes(layout_.getSplitterBottom()); // we're already in normal if the splitter is being invoked if (topState != WindowState.NORMAL) { topWindowStateChangeManager_.onWindowStateChange( new WindowStateChangeEvent(topState)); } eventBus.fireEvent(new GlassVisibilityEvent(false)); } }); } } // resize the panes based on the specified bottom height and return the // new window state for the top pane (this implements snap to minimize) private WindowState resizePanes(int bottom) { WindowState topState = null; int height = layout_.getOffsetHeight(); // If the height of upper or lower panel is smaller than this // then that panel will minimize final int MIN_HEIGHT = 60; if (bottom < MIN_HEIGHT) { topState = WindowState.MAXIMIZE; normalHeight_ = snapMinimizeNormalHeight_; } else if (bottom >= height - MIN_HEIGHT) { topState = WindowState.MINIMIZE; normalHeight_ = snapMinimizeNormalHeight_; } else { topState = WindowState.NORMAL; normalHeight_ = new NormalHeight(bottom, height, Window.getClientHeight()); } session_.persistClientState(); return topState; } private void hookEvents() { registrations_.add( windowA_.addWindowStateChangeHandler(topWindowStateChangeManager_)); registrations_.add( windowB_.addWindowStateChangeHandler(bottomWindowStateChangeManager_)); registrations_.add( windowA_.addEnsureHeightHandler(new EnsureHeightChangeManager(true))); registrations_.add( windowB_.addEnsureHeightHandler(new EnsureHeightChangeManager(false))); } private void unhookEvents() { registrations_.removeHandler(); } public void replaceWindows(LogicalWindow windowA, LogicalWindow windowB) { unhookEvents(); windowA_ = windowA; windowB_ = windowB; hookEvents(); layout_.setWidgets(new Widget[] { windowA_.getNormal(), windowA_.getMinimized(), windowB_.getNormal(), windowB_.getMinimized() }); Scheduler.get().scheduleFinally(new ScheduledCommand() { public void execute() { windowA_.onWindowStateChange(new WindowStateChangeEvent(NORMAL)); } }); } public void onResize() { if (layout_ != null) { layout_.onResize(); } } private void layout(final LogicalWindow top, final LogicalWindow bottom, boolean keepFocus) { AnimationHelper.create(layout_, top, bottom, normalHeight_.getHeightScaledTo(getOffsetHeight()), layout_.getSplitterHeight(), isVisible() && isAttached(), keepFocus).animate(); } public void setTopWindowState(WindowState state) { topWindowStateChangeManager_.onWindowStateChange( new WindowStateChangeEvent(state)); } private class EnsureHeightChangeManager implements EnsureHeightHandler { public EnsureHeightChangeManager(boolean isTopWindow) { isTopWindow_ = isTopWindow; } @Override public void onEnsureHeight(EnsureHeightEvent event) { // constants final int FRAME = 52; final int MINIMUM = 160; // get the target window and target height LogicalWindow targetWindow = isTopWindow_ ? windowA_ : windowB_; int targetHeight = event.getHeight() + FRAME; // ignore if we are already maximized if (targetWindow.getState() == WindowState.MAXIMIZE) return; // ignore if we are already high enough if (targetWindow.getActiveWidget().getOffsetHeight() >= targetHeight) return; // calculate height of other pane int aHeight = windowA_.getActiveWidget().getOffsetHeight(); int bHeight = windowB_.getActiveWidget().getOffsetHeight(); int chromeHeight = layout_.getOffsetHeight() - aHeight - bHeight; int otherHeight = layout_.getOffsetHeight() - chromeHeight - targetHeight; // see if we need to offset to acheive minimum other height int offset = 0; if (otherHeight < MINIMUM) offset = MINIMUM - otherHeight; // determine the height (only the bottom can be sizes explicitly // so for the top we need to derive it's height from the implied // bottom height that we already computed) int height = isTopWindow_ ? (otherHeight + offset) : (targetHeight - offset); // ignore if this will reduce our size if (height <= targetWindow.getActiveWidget().getOffsetHeight()) return; // resize bottom WindowState topState = resizePanes(height); if (topState != null) { topWindowStateChangeManager_.onWindowStateChange( new WindowStateChangeEvent(topState)); } } private boolean isTopWindow_; } private BinarySplitLayoutPanel layout_; private NormalHeight normalHeight_; private LogicalWindow windowA_; private LogicalWindow windowB_; private final Session session_; private WindowStateChangeManager topWindowStateChangeManager_; private WindowStateChangeHandler bottomWindowStateChangeManager_; private HandlerRegistrations registrations_ = new HandlerRegistrations(); private NormalHeight snapMinimizeNormalHeight_; }
package com.astoev.cave.survey.activity.home; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import com.astoev.cave.survey.Constants; import com.astoev.cave.survey.R; import com.astoev.cave.survey.activity.MainMenuActivity; import com.astoev.cave.survey.activity.UIUtilities; import com.astoev.cave.survey.activity.main.PointActivity; import com.astoev.cave.survey.model.Gallery; import com.astoev.cave.survey.model.Leg; import com.astoev.cave.survey.model.Option; import com.astoev.cave.survey.model.Point; import com.astoev.cave.survey.model.Project; import com.astoev.cave.survey.service.Options; import com.astoev.cave.survey.service.orientation.OrientationProcessorFactory; import com.astoev.cave.survey.util.DaoUtil; import com.astoev.cave.survey.util.PointUtil; import com.j256.ormlite.misc.TransactionManager; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; public class NewProjectActivity extends MainMenuActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.newproject); // populate spinners // distance prepareSpinner(R.id.options_units_distance, R.array.distance_units); prepareSpinner(R.id.options_distance_type, R.array.distance_read_type); // azimuth prepareSpinner(R.id.options_units_azimuth, R.array.azimuth_units); // check if build in orientation sensor is available boolean hasBuildInOrientationProcessor = OrientationProcessorFactory.canReadOrientation(this); int azimuthOptions = R.array.azimuth_read_type_all; int slopepeOptions = R.array.slope_read_type_all; if (!hasBuildInOrientationProcessor){ azimuthOptions = R.array.azimuth_read_type_manually; slopepeOptions = R.array.slope_read_type; } prepareSpinner(R.id.options_azimuth_type, azimuthOptions); // slope prepareSpinner(R.id.options_units_slope, R.array.slope_units); prepareSpinner(R.id.options_slope_type, slopepeOptions); } /** * @see com.astoev.cave.survey.activity.BaseActivity#getScreenTitle() */ @Override protected String getScreenTitle() { return getString(R.string.new_title); } private void prepareSpinner(int aSpinnerId, int aTextArrayId) { Spinner spinner = (Spinner) findViewById(aSpinnerId); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, aTextArrayId, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } private int getSpinnerValue(int aSpinnerId) { Spinner spinner = (Spinner) findViewById(aSpinnerId); return spinner.getSelectedItemPosition(); } public void createNewProject() { try { Log.v(Constants.LOG_TAG_UI, "Creating project"); EditText projectNameField = (EditText) findViewById(R.id.new_projectname); final String newProjectName = projectNameField.getText().toString(); if (newProjectName.trim().equals("")) { projectNameField.setError(getString(R.string.new_project_name_required)); return; } //check existing List<Project> sameNameProjects = getWorkspace().getDBHelper().getProjectDao().queryForEq(Project.COLUMN_NAME, newProjectName); if (sameNameProjects.size() > 0) { projectNameField.setHint(R.string.home_button_new_exists); projectNameField.setError(getString(R.string.home_button_new_exists, newProjectName)); return; } Project project = TransactionManager.callInTransaction(getWorkspace().getDBHelper().getConnectionSource(), new Callable<Project>() { public Project call() throws SQLException { // project Project newProject = new Project(); newProject.setName(newProjectName); newProject.setCreationDate(new Date()); getWorkspace().getDBHelper().getProjectDao().create(newProject); getWorkspace().setActiveProject(newProject); // gallery Gallery firstGallery = DaoUtil.createGallery(true); // points Point startPoint = PointUtil.createFirstPoint(); getWorkspace().getDBHelper().getPointDao().create(startPoint); Point secondPoint = PointUtil.createSecondPoint(); getWorkspace().getDBHelper().getPointDao().create(secondPoint); // first leg Leg firstLeg = new Leg(startPoint, secondPoint, newProject, firstGallery.getId()); getWorkspace().getDBHelper().getLegDao().create(firstLeg); getWorkspace().setActiveLeg(firstLeg); // project units // distance switch (getSpinnerValue(R.id.options_units_distance)) { case 0: Log.i(Constants.LOG_TAG_UI, "Using meters for distance"); Options.createOption(Option.CODE_DISTANCE_UNITS, Option.UNIT_METERS); } switch (getSpinnerValue(R.id.options_distance_type)) { case 0: Log.i(Constants.LOG_TAG_UI, "Read distance manually"); Options.createOption(Option.CODE_DISTANCE_SENSOR, Option.CODE_SENSOR_NONE); break; case 1: Log.i(Constants.LOG_TAG_UI, "Read distance from BT"); Options.createOption(Option.CODE_DISTANCE_SENSOR, Option.CODE_SENSOR_BLUETOOTH); } // azimuth switch (getSpinnerValue(R.id.options_units_azimuth)) { case 0: Log.i(Constants.LOG_TAG_UI, "Using degrees for azimuth"); Options.createOption(Option.CODE_AZIMUTH_UNITS, Option.UNIT_DEGREES); break; case 1: Log.i(Constants.LOG_TAG_UI, "Using grads for azimuth"); Options.createOption(Option.CODE_AZIMUTH_UNITS, Option.UNIT_GRADS); } switch (getSpinnerValue(R.id.options_azimuth_type)) { case 0: Log.i(Constants.LOG_TAG_UI, "Read azimuth manually"); Options.createOption(Option.CODE_AZIMUTH_SENSOR, Option.CODE_SENSOR_NONE); break; case 1: Log.i(Constants.LOG_TAG_UI, "Read azimuth from build-in sensor"); Options.createOption(Option.CODE_AZIMUTH_SENSOR, Option.CODE_SENSOR_INTERNAL); } // slope switch (getSpinnerValue(R.id.options_units_slope)) { case 0: Log.i(Constants.LOG_TAG_UI, "Using degrees for slope"); Options.createOption(Option.CODE_SLOPE_UNITS, Option.UNIT_DEGREES); break; case 1: Log.i(Constants.LOG_TAG_UI, "Using grads for slope"); Options.createOption(Option.CODE_SLOPE_UNITS, Option.UNIT_GRADS); } switch (getSpinnerValue(R.id.options_slope_type)) { case 0: Log.i(Constants.LOG_TAG_UI, "Read slope manually"); Options.createOption(Option.CODE_SLOPE_SENSOR, Option.CODE_SENSOR_NONE); break; case 1: Log.i(Constants.LOG_TAG_UI, "Read slope from BT"); Options.createOption(Option.CODE_SLOPE_SENSOR, Option.CODE_SENSOR_BLUETOOTH); break; case 2: Log.i(Constants.LOG_TAG_UI, "Read slope from build-in sensor"); Options.createOption(Option.CODE_SLOPE_SENSOR, Option.CODE_SENSOR_INTERNAL); break; } return newProject; } }); if (project != null) { Intent intent = new Intent(NewProjectActivity.this, PointActivity.class); getWorkspace().setActiveProject(project); getWorkspace().setActiveLeg(getWorkspace().getActiveOrFirstLeg()); intent.putExtra(Constants.LEG_SELECTED, getWorkspace().getActiveLegId()); startActivity(intent); finish(); } else { Log.e(Constants.LOG_TAG_DB, "No project created"); UIUtilities.showNotification(R.string.error); } } catch (Exception e) { Log.e(Constants.LOG_TAG_UI, "Failed at new project creation", e); UIUtilities.showNotification(R.string.error); } } /** * @see com.astoev.cave.survey.activity.MainMenuActivity#getChildsOptionsMenu() */ @Override protected int getChildsOptionsMenu() { return R.menu.newprojectmenu; } /** * Don't want to see base menu items * * @see com.astoev.cave.survey.activity.MainMenuActivity#showBaseOptionsMenu() */ @Override protected boolean showBaseOptionsMenu() { return false; } /** * @see com.astoev.cave.survey.activity.MainMenuActivity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { Log.i(Constants.LOG_TAG_UI, "NewProject activity's menu selected - " + item.toString()); switch (item.getItemId()) { case R.id.new_action_create : { createNewProject(); return true; } default: return super.onOptionsItemSelected(item); } } }
package org.xtreemfs.mrc.stages; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.xtreemfs.common.auth.AuthenticationException; import org.xtreemfs.common.auth.UserCredentials; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.Auth; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.MessageType; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno; import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader; import org.xtreemfs.foundation.pbrpc.server.RPCServerRequest; import org.xtreemfs.mrc.ErrorRecord; import org.xtreemfs.mrc.MRCException; import org.xtreemfs.mrc.MRCRequest; import org.xtreemfs.mrc.MRCRequestDispatcher; import org.xtreemfs.mrc.UserException; import org.xtreemfs.mrc.database.DatabaseException; import org.xtreemfs.mrc.database.DatabaseException.ExceptionType; import org.xtreemfs.mrc.operations.AccessOperation; import org.xtreemfs.mrc.operations.AddReplicaOperation; import org.xtreemfs.mrc.operations.CheckFileListOperation; import org.xtreemfs.mrc.operations.CheckpointOperation; import org.xtreemfs.mrc.operations.CreateDirOperation; import org.xtreemfs.mrc.operations.CreateLinkOperation; import org.xtreemfs.mrc.operations.CreateSymLinkOperation; import org.xtreemfs.mrc.operations.CreateVolumeOperation; import org.xtreemfs.mrc.operations.DeleteOperation; import org.xtreemfs.mrc.operations.DeleteVolumeOperation; import org.xtreemfs.mrc.operations.DumpDBOperation; import org.xtreemfs.mrc.operations.FSetAttrOperation; import org.xtreemfs.mrc.operations.GetLocalVolumesOperation; import org.xtreemfs.mrc.operations.GetSuitableOSDsOperation; import org.xtreemfs.mrc.operations.GetXAttrOperation; import org.xtreemfs.mrc.operations.GetXAttrsOperation; import org.xtreemfs.mrc.operations.GetXLocListOperation; import org.xtreemfs.mrc.operations.InternalDebugOperation; import org.xtreemfs.mrc.operations.MRCOperation; import org.xtreemfs.mrc.operations.MoveOperation; import org.xtreemfs.mrc.operations.OpenOperation; import org.xtreemfs.mrc.operations.ReadDirAndStatOperation; import org.xtreemfs.mrc.operations.ReadLinkOperation; import org.xtreemfs.mrc.operations.RemoveReplicaOperation; import org.xtreemfs.mrc.operations.RemoveXAttrOperation; import org.xtreemfs.mrc.operations.RenewOperation; import org.xtreemfs.mrc.operations.RestoreDBOperation; import org.xtreemfs.mrc.operations.RestoreFileOperation; import org.xtreemfs.mrc.operations.SetReadOnlyXattrOperation; import org.xtreemfs.mrc.operations.SetReplicaUpdatePolicyOperation; import org.xtreemfs.mrc.operations.SetXAttrOperation; import org.xtreemfs.mrc.operations.SetattrOperation; import org.xtreemfs.mrc.operations.ShutdownOperation; import org.xtreemfs.mrc.operations.GetFileCredentialsOperation; import org.xtreemfs.mrc.operations.StatFSOperation; import org.xtreemfs.mrc.operations.StatOperation; import org.xtreemfs.mrc.operations.StatusPageOperation; import org.xtreemfs.mrc.operations.TruncateOperation; import org.xtreemfs.mrc.operations.UpdateFileSizeOperation; import org.xtreemfs.pbrpc.generatedinterfaces.MRCServiceConstants; import com.google.protobuf.Descriptors.FieldDescriptor; /** * * @author bjko */ public class ProcessingStage extends MRCStage { public static final int STAGEOP_PARSE_AND_EXECUTE = 1; private final MRCRequestDispatcher master; private final Map<Integer, MRCOperation> operations; private final Map<Integer, Integer> _opCountMap; private final boolean statisticsEnabled = true; public ProcessingStage(MRCRequestDispatcher master) { super("ProcSt"); this.master = master; operations = new HashMap<Integer, MRCOperation>(); installOperations(); if (statisticsEnabled) { // initialize operations counter _opCountMap = new HashMap<Integer, Integer>(); for (Integer i : operations.keySet()) _opCountMap.put(i, 0); } } public void installOperations() { operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_SHUTDOWN, new ShutdownOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_MKVOL, new CreateVolumeOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_RMVOL, new DeleteVolumeOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_LSVOL, new GetLocalVolumesOperation(master)); operations.put(MRCServiceConstants.PROC_ID_GETATTR, new StatOperation(master)); operations.put(MRCServiceConstants.PROC_ID_READDIR, new ReadDirAndStatOperation(master)); operations.put(MRCServiceConstants.PROC_ID_MKDIR, new CreateDirOperation(master)); operations.put(MRCServiceConstants.PROC_ID_SYMLINK, new CreateSymLinkOperation(master)); operations.put(MRCServiceConstants.PROC_ID_UNLINK, new DeleteOperation(master)); operations.put(MRCServiceConstants.PROC_ID_RMDIR, new DeleteOperation(master)); operations.put(MRCServiceConstants.PROC_ID_GETXATTR, new GetXAttrOperation(master)); operations.put(MRCServiceConstants.PROC_ID_LISTXATTR, new GetXAttrsOperation(master)); operations.put(MRCServiceConstants.PROC_ID_SETXATTR, new SetXAttrOperation(master)); operations.put(MRCServiceConstants.PROC_ID_REMOVEXATTR, new RemoveXAttrOperation(master)); operations.put(MRCServiceConstants.PROC_ID_OPEN, new OpenOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_RENEW_CAPABILITY, new RenewOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_REPLICA_ADD, new AddReplicaOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_REPLICA_REMOVE, new RemoveReplicaOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_REPLICA_LIST, new GetXLocListOperation(master)); operations.put(MRCServiceConstants.PROC_ID_RENAME, new MoveOperation(master)); operations.put(MRCServiceConstants.PROC_ID_LINK, new CreateLinkOperation(master)); operations.put(MRCServiceConstants.PROC_ID_STATVFS, new StatFSOperation(master)); operations.put(MRCServiceConstants.PROC_ID_READLINK, new ReadLinkOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_DUMP_DATABASE, new DumpDBOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_RESTORE_DATABASE, new RestoreDBOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_CHECK_FILE_EXISTS, new CheckFileListOperation( master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_RESTORE_FILE, new RestoreFileOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_CHECKPOINT, new CheckpointOperation(master)); operations.put(MRCServiceConstants.PROC_ID_SETATTR, new SetattrOperation(master)); operations.put(MRCServiceConstants.PROC_ID_FSETATTR, new FSetAttrOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_GET_SUITABLE_OSDS, new GetSuitableOSDsOperation( master)); operations.put(MRCServiceConstants.PROC_ID_FTRUNCATE, new TruncateOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_INTERNAL_DEBUG, new InternalDebugOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_UPDATE_FILE_SIZE, new UpdateFileSizeOperation(master)); operations.put(MRCServiceConstants.PROC_ID_ACCESS, new AccessOperation(master)); // TODO operations.put(replication_toMasterRequest.TAG, new // ReplicationToMasterOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_SET_REPLICA_UPDATE_POLICY, new SetReplicaUpdatePolicyOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_SET_READ_ONLY_XATTR, new SetReadOnlyXattrOperation(master)); operations.put(MRCServiceConstants.PROC_ID_XTREEMFS_GET_FILE_CREDENTIALS, new GetFileCredentialsOperation(master)); } public Map<Integer, Integer> get_opCountMap() { return _opCountMap; } // public String getOpName(int opId) { // String opName = operations.get(opId).getClass().getSimpleName(); // return (opName.charAt(0) + "").toLowerCase() + opName.substring(0, opName.length() - "Operation".length()).substring(1); @Override protected void processMethod(StageMethod method) { switch (method.getStageMethod()) { case STAGEOP_PARSE_AND_EXECUTE: parseAndExecute(method); break; default: method.getRq().setError(ErrorType.INTERNAL_SERVER_ERROR, "unknown stage operation"); master.requestFinished(method.getRq()); } } /** * Parse request and execute method * * @param method * stagemethod to execute */ private void parseAndExecute(StageMethod method) { final MRCRequest rq = method.getRq(); final RPCServerRequest rpcRequest = rq.getRPCRequest(); final RPCHeader header = rpcRequest.getHeader(); final RPCHeader.RequestHeader rqHeader = header.getRequestHeader(); if (header.getMessageType() != MessageType.RPC_REQUEST) { rq.setError(ErrorType.GARBAGE_ARGS, POSIXErrno.POSIX_ERROR_EIO, "expected RPC request message type but got " + header.getMessageType()); return; } final MRCOperation op = operations.get(rqHeader.getProcId()); if (op == null) { rq.setError(ErrorType.INVALID_PROC_ID, "requested operation (" + rqHeader.getProcId() + ") is not available on this MRC"); master.requestFinished(rq); return; } if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "operation for request %s: %s", rq .toString(), op.getClass().getSimpleName()); if (statisticsEnabled) { _opCountMap.put(rqHeader.getProcId(), _opCountMap.get(rqHeader.getProcId()) + 1); } // parse request arguments ErrorRecord error = op.parseRequestArgs(rq); if (error != null) { rq.setError(error); master.requestFinished(rq); return; } try { // get the auth data if available Auth auth = header.getRequestHeader().hasAuthData() ? header.getRequestHeader().getAuthData() : null; // get the user credentials org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials ctx = op .getUserCredentials(rq); if (ctx != null) try { UserCredentials cred = master.getAuthProvider().getEffectiveCredentials(ctx, rpcRequest.getConnection().getChannel()); rq.getDetails().superUser = cred.isSuperUser(); rq.getDetails().groupIds = cred.getGroupIDs(); rq.getDetails().userId = cred.getUserID(); rq.getDetails().auth = auth; rq.getDetails().password = auth != null && auth.hasAuthPasswd() ? auth.getAuthPasswd() .getPassword() : ""; } catch (AuthenticationException ex) { throw new UserException(POSIXErrno.POSIX_ERROR_EPERM, ex.getMessage()); } } catch (Exception exc) { method.getRq().setError(ErrorType.INTERNAL_SERVER_ERROR, "could not initialize authentication module", exc); master.requestFinished(method.getRq()); return; } try { if (Logging.isDebug()) { StringBuffer params = new StringBuffer(); Map<FieldDescriptor, Object> fieldMap = rq.getRequestArgs() == null ? null : rq .getRequestArgs().getAllFields(); if (fieldMap != null) { int i = 0; for (Entry<FieldDescriptor, Object> entry : fieldMap.entrySet()) { params.append(entry.getKey().getName() + "='" + entry.getValue() + (i == fieldMap.size() - 1 ? "'" : "', ")); i++; } } Logging.logMessage(Logging.LEVEL_DEBUG, this, "parsed request: %s (%s)\n", StatusPageOperation.getOpName(rqHeader.getProcId()), params.toString()); } op.startRequest(rq); } catch (UserException exc) { reportUserError(op, rq, exc, exc.getErrno()); } catch (MRCException exc) { Throwable cause = exc.getCause(); if (cause instanceof DatabaseException && ((DatabaseException) cause).getType() == ExceptionType.NOT_ALLOWED) reportUserError(op, rq, exc, POSIXErrno.POSIX_ERROR_EPERM); else reportServerError(op, rq, exc); } catch (DatabaseException exc) { if (exc.getType() == ExceptionType.NOT_ALLOWED) { reportUserError(op, rq, exc, POSIXErrno.POSIX_ERROR_EPERM); } else if (exc.getType() == ExceptionType.REDIRECT) { try { redirect(rq, exc.getAttachment() != null? (String) exc.getAttachment(): master.getReplMasterUUID()); } catch (MRCException e) { reportServerError(op, rq, e); } } else reportServerError(op, rq, exc); } catch (Throwable exc) { reportServerError(op, rq, exc); } } private void reportUserError(MRCOperation op, MRCRequest rq, Throwable exc, POSIXErrno errno) { if (Logging.isDebug()) Logging.logUserError(Logging.LEVEL_DEBUG, Category.proc, this, exc); op.finishRequest(rq, new ErrorRecord(ErrorType.ERRNO, errno, exc.getMessage(), exc)); } private void reportServerError(MRCOperation op, MRCRequest rq, Throwable exc) { if (Logging.isDebug()) Logging.logUserError(Logging.LEVEL_DEBUG, Category.proc, this, exc); op.finishRequest(rq, new ErrorRecord(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_NONE, "An error has occurred at the MRC. Details: " + exc.getMessage(), exc)); } private void redirect(MRCRequest rq, String uuid) { rq.getRPCRequest().sendRedirect(uuid); } }
package org.jivesoftware.messenger.container; import org.jivesoftware.messenger.XMPPServer; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.mortbay.http.SunJsseListener; import org.mortbay.http.HttpListener; import org.mortbay.http.HttpContext; import org.mortbay.jetty.Server; import org.mortbay.log.Factory; import org.mortbay.log.LogImpl; import org.mortbay.log.OutputStreamLogSink; import org.mortbay.util.InetAddrPort; import java.io.File; /** * The admin console plugin. It starts a Jetty instance on the configured * port and loads the admin console web application. * * @author Matt Tucker */ public class AdminConsolePlugin implements Plugin { private static Server jetty = null; private int port; private int securePort; private File pluginDir; private HttpContext context = null; private HttpListener plainListener = null; private HttpListener secureListener = null; /** * Create a jetty module. */ public AdminConsolePlugin() { } public void restartListeners() { try { String restarting = LocaleUtils.getLocalizedString("admin.console.restarting"); System.out.println(restarting); Log.info(restarting); jetty.stop(); if (plainListener != null) { jetty.removeListener(plainListener); plainListener = null; } if (secureListener != null) { jetty.removeListener(secureListener); secureListener = null; } jetty.removeContext(context); loadListeners(); // Add web-app context = jetty.addWebApplication("/", pluginDir.getAbsoluteFile() + File.separator + "webapp"); context.setWelcomeFiles(new String[]{"index.jsp"}); jetty.start(); printListenerMessages(); } catch (Exception e) { Log.error(e); } } private void loadListeners() throws Exception { // Configure HTTP socket listener. Setting the interface property to a // non null value will imply that the Jetty server will only // accept connect requests to that IP address. String interfaceName = JiveGlobals.getXMLProperty("adminConsole.interface"); port = JiveGlobals.getXMLProperty("adminConsole.port", 9090); InetAddrPort address = new InetAddrPort(interfaceName, port); if (port > 0) { plainListener = jetty.addListener(address); } try { securePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091); if (securePort > 0) { SunJsseListener listener = new SunJsseListener(); // Get the keystore location. The default location is security/keystore String keyStoreLocation = JiveGlobals.getProperty("xmpp.socket.ssl.keystore", "resources" + File.separator + "security" + File.separator + "keystore"); // The location is relative to the home directory of the application. keyStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + keyStoreLocation; // Get the keystore password. The default password is "changeit". String keypass = JiveGlobals.getProperty("xmpp.socket.ssl.keypass", "changeit"); keypass = keypass.trim(); listener.setKeystore(keyStoreLocation); listener.setKeyPassword(keypass); listener.setPassword(keypass); listener.setHost(interfaceName); listener.setPort(securePort); secureListener = jetty.addListener(listener); } } catch (Exception e) { Log.error(e); } } public void initializePlugin(PluginManager manager, File pluginDir) { this.pluginDir = pluginDir; try { // Configure logging to a file, creating log dir if needed System.setProperty("org.apache.commons.logging.LogFactory", "org.mortbay.log.Factory"); File logDir = new File(JiveGlobals.getHomeDirectory(), "logs"); if (!logDir.exists()) { logDir.mkdirs(); } File logFile = new File(logDir, "admin-console.log"); OutputStreamLogSink logSink = new OutputStreamLogSink(logFile.toString()); logSink.start(); LogImpl log = (LogImpl) Factory.getFactory().getInstance(""); // Ignore INFO logs unless debugging turned on. if (!Log.isDebugEnabled()) { log.setVerbose(-1); } else { log.setVerbose(1); } log.add(logSink); jetty = new Server(); loadListeners(); // Add web-app context = jetty.addWebApplication("/", pluginDir.getAbsoluteFile() + File.separator + "webapp"); context.setWelcomeFiles(new String[]{"index.jsp"}); jetty.start(); printListenerMessages(); } catch (Exception e) { System.err.println("Error starting admin console: " + e.getMessage()); Log.error("Trouble initializing admin console", e); } } public void destroyPlugin() { plainListener = null; secureListener = null; try { if (jetty != null) { jetty.stop(); jetty = null; } } catch (InterruptedException e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } } /** * Returns the Jetty instance started by this plugin. * * @return the Jetty server instance. */ public static Server getJettyServer() { return jetty; } /** * Writes out startup messages for the listeners. */ private void printListenerMessages() { String warning = LocaleUtils.getLocalizedString("admin.console.warning"); String listening = LocaleUtils.getLocalizedString("admin.console.listening"); if (plainListener == null && secureListener == null) { Log.info(warning); System.out.println(warning); } else if (plainListener == null && secureListener != null) { Log.info(listening + " https: XMPPServer.getInstance().getServerInfo().getName() + ":" + securePort); System.out.println(listening + " https: XMPPServer.getInstance().getServerInfo().getName() + ":" + securePort); } else if (secureListener == null && plainListener != null) { Log.info(listening + " http: XMPPServer.getInstance().getServerInfo().getName() + ":" + port); System.out.println(listening + " http: XMPPServer.getInstance().getServerInfo().getName() + ":" + port); } else { String msg = listening + ":\n" + " http://" + XMPPServer.getInstance().getServerInfo().getName() + ":" + port + "\n" + " https://" + XMPPServer.getInstance().getServerInfo().getName() + ":" + securePort; Log.info(msg); System.out.println(msg); } } }
package joliex.ui; import javax.swing.JOptionPane; import jolie.runtime.JavaService; import jolie.runtime.embedding.RequestResponse; public class SwingService extends JavaService { @RequestResponse public void showMessageDialog( String message ) { JOptionPane.showMessageDialog( null, message ); } public Integer showYesNoQuestionDialog( String message ) { return JOptionPane.showOptionDialog( null, message, "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null ); } public String showInputDialog( String message ) { return JOptionPane.showInputDialog( message ); } }
package org.jivesoftware.openfire.session; import org.dom4j.Element; import org.dom4j.io.XMPPPacketReader; import org.jivesoftware.openfire.Connection; import org.jivesoftware.openfire.PacketException; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.StreamID; import org.jivesoftware.openfire.auth.AuthFactory; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.openfire.component.ExternalComponentManager; import org.jivesoftware.openfire.component.InternalComponentManager; import org.jivesoftware.openfire.net.SocketConnection; import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.Log; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmpp.component.ComponentManager; import org.xmpp.packet.JID; import org.xmpp.packet.Packet; import org.xmpp.packet.StreamError; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Represents a session between the server and a component. * * @author Gaston Dombiak */ public class LocalComponentSession extends LocalSession implements ComponentSession { private LocalExternalComponent component; /** * Returns a newly created session between the server and a component. The session will be * created and returned only if all the checkings were correct.<p> * * A domain will be binded for the new connecting component. This method is following * the JEP-114 where the domain to bind is sent in the TO attribute of the stream header. * * @param serverName the name of the server where the session is connecting to. * @param reader the reader that is reading the provided XML through the connection. * @param connection the connection with the component. * @return a newly created session between the server and a component. */ public static LocalComponentSession createSession(String serverName, XMPPPacketReader reader, SocketConnection connection) throws UnauthorizedException, IOException, XmlPullParserException { XmlPullParser xpp = reader.getXPPParser(); String domain = xpp.getAttributeValue("", "to"); Log.debug("[ExComp] Starting registration of new external component for domain: " + domain); Writer writer = connection.getWriter(); // Default answer header in case of an error StringBuilder sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='"); sb.append(CHARSET); sb.append("'?>"); sb.append("<stream:stream "); sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" "); sb.append("xmlns=\"jabber:component:accept\" from=\""); sb.append(domain); sb.append("\">"); // Check that a domain was provided in the stream header if (domain == null) { Log.debug("[ExComp] Domain not specified in stanza: " + xpp.getText()); // Include the bad-format in the response StreamError error = new StreamError(StreamError.Condition.bad_format); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Get the requested subdomain String subdomain = domain; int index = domain.indexOf(serverName); if (index > -1) { subdomain = domain.substring(0, index -1); } domain = subdomain + "." + serverName; JID componentJID = new JID(domain); // Check that an external component for the specified subdomain may connect to this server if (!ExternalComponentManager.canAccess(subdomain)) { Log.debug("[ExComp] Component is not allowed to connect with subdomain: " + subdomain); StreamError error = new StreamError(StreamError.Condition.host_unknown); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Check that a secret key was configured in the server String secretKey = ExternalComponentManager.getSecretForComponent(subdomain); if (secretKey == null) { Log.debug("[ExComp] A shared secret for the component was not found."); // Include the internal-server-error in the response StreamError error = new StreamError(StreamError.Condition.internal_server_error); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Check that the requested subdomain is not already in use if (InternalComponentManager.getInstance().hasComponent(componentJID)) { Log.debug("[ExComp] Another component is already using domain: " + domain); // Domain already occupied so return a conflict error and close the connection // Include the conflict error in the response StreamError error = new StreamError(StreamError.Condition.conflict); sb.append(error.toXML()); writer.write(sb.toString()); writer.flush(); // Close the underlying connection connection.close(); return null; } // Create a ComponentSession for the external component LocalComponentSession session = SessionManager.getInstance().createComponentSession(componentJID, connection); session.component = new LocalExternalComponent(session, connection); try { Log.debug("[ExComp] Send stream header with ID: " + session.getStreamID() + " for component with domain: " + domain); // Build the start packet response sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='"); sb.append(CHARSET); sb.append("'?>"); sb.append("<stream:stream "); sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" "); sb.append("xmlns=\"jabber:component:accept\" from=\""); sb.append(domain); sb.append("\" id=\""); sb.append(session.getStreamID().toString()); sb.append("\">"); writer.write(sb.toString()); writer.flush(); // Perform authentication. Wait for the handshake (with the secret key) Element doc = reader.parseDocument().getRootElement(); String digest = "handshake".equals(doc.getName()) ? doc.getStringValue() : ""; String anticipatedDigest = AuthFactory.createDigest(session.getStreamID().getID(), secretKey); // Check that the provided handshake (secret key + sessionID) is correct if (!anticipatedDigest.equalsIgnoreCase(digest)) { Log.debug("[ExComp] Incorrect handshake for component with domain: " + domain); // The credentials supplied by the initiator are not valid (answer an error // and close the connection) writer.write(new StreamError(StreamError.Condition.not_authorized).toXML()); writer.flush(); // Close the underlying connection connection.close(); return null; } else { // Component has authenticated fine session.setStatus(STATUS_AUTHENTICATED); // Send empty handshake element to acknowledge success writer.write("<handshake></handshake>"); writer.flush(); // Bind the domain to this component ExternalComponent component = session.getExternalComponent(); InternalComponentManager.getInstance().addComponent(subdomain, component); Log.debug("[ExComp] External component was registered SUCCESSFULLY with domain: " + domain); return session; } } catch (Exception e) { Log.error("An error occured while creating a ComponentSession", e); // Close the underlying connection connection.close(); return null; } } public LocalComponentSession(String serverName, Connection conn, StreamID id) { super(serverName, conn, id); } public String getAvailableStreamFeatures() { // Nothing special to add return null; } boolean canProcess(Packet packet) { return true; } void deliver(Packet packet) throws PacketException { component.deliver(packet); } public ExternalComponent getExternalComponent() { return component; } /** * The ExternalComponent acts as a proxy of the remote connected component. Any Packet that is * sent to this component will be delivered to the real component on the other side of the * connection.<p> * * An ExternalComponent will be added as a route in the RoutingTable for each connected * external component. This implies that when the server receives a packet whose domain matches * the external component services address then a route to the external component will be used * and the packet will be forwarded to the component on the other side of the connection. * * @author Gaston Dombiak */ public static class LocalExternalComponent implements ComponentSession.ExternalComponent { private LocalComponentSession session; private Connection connection; private String name = ""; private String type = ""; private String category = ""; /** * List of subdomains that were binded for this component. The list will include * the initial subdomain. */ private List<String> subdomains = new ArrayList<String>(); public LocalExternalComponent(LocalComponentSession session, Connection connection) { this.session = session; this.connection = connection; } public void processPacket(Packet packet) { // Ask the session to process the outgoing packet. This will // give us the chance to apply PacketInterceptors session.process(packet); } /** * Delivers the packet to the external component. * * @param packet the packet to deliver. */ void deliver(Packet packet) { if (connection != null && !connection.isClosed()) { try { connection.deliver(packet); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); connection.close(); } } } public String getName() { return name; } public String getDescription() { return category + " - " + type; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getInitialSubdomain() { if (subdomains.isEmpty()) { return null; } return subdomains.get(0); } private void addSubdomain(String subdomain) { subdomains.add(subdomain); } public Collection<String> getSubdomains() { return subdomains; } public void initialize(JID jid, ComponentManager componentManager) { addSubdomain(jid.toString()); } public void start() { } public void shutdown() { } public String toString() { return super.toString() + " - subdomains: " + subdomains; } } }
package org.ccnx.ccn.profiles.repo; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.repo.RepositoryInfo; import org.ccnx.ccn.impl.repo.RepositoryInfo.RepoInfoType; import org.ccnx.ccn.impl.support.DataUtils; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.CCNAbstractInputStream; import org.ccnx.ccn.io.content.CCNNetworkObject; import org.ccnx.ccn.io.content.ContentDecodingException; import org.ccnx.ccn.io.content.PublicKeyObject; import org.ccnx.ccn.io.content.Link.LinkObject; import org.ccnx.ccn.profiles.CommandMarker; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.SignedInfo.ContentType; /** * Provides support for controlling repository functions beyond * the basic operations for writing data from an application * into a repository supported by classes in the org.ccnx.ccn.io * package. * @author jthornto * */ public class RepositoryControl { /** * Temporary cache of blocks we have synced, to avoid double-syncing blocks. */ protected static Set<ContentName> syncedObjects = Collections.synchronizedSet(new HashSet<ContentName>()); /** * Request that a local repository preserve a copy * of the exact contents of a given stream opened for reading * with a given handle, and all links that were dereferenced * to read the stream. * * A local repository is one connected * directly to the same ccnd as the given handle; such a repository * is likely to be special in the sense that it may be available to local * applications even when there is no connectivity beyond the local * machine. An application reading certain content that it did not originate * may have reason to need that content to be available reliably as connectivity changes * in the future. Since the application is not the source of the content, it need * only ask the local repository to be interested in it rather than creating an * output stream to write it. This method serves that purpose. * * This method is experimental and the way of addressing this problem * is likely to change in the future. * * This method may fail (IOException) if the local repository is not already * configured to support holding the data in question. For example, the * repository policy might not admit the namespace in question * and this method does not override such overall policy. * * There may be more than one local repository but this method does not * presently distinguish one if that is the case. Any one local repository * that is available may be used, and at most one should be expected to respond to * the request. This method should verify that a confirmation is from an acceptable * local repository. * * If the repository already holds the content it may confirm immediately, otherwise the repository * will begin to retrieve and store the content but there is no guarantee that this is complete * upon return from this method. The return value indicates whether data is already confirmed. * * @param handle the handle * @param stream The stream for which the content should be preserved * @return boolean true iff confirmation received from repository * @throws IOException if no repository responds or another communication error occurs */ public static boolean localRepoSync(CCNHandle handle, CCNAbstractInputStream stream) throws IOException { return localRepoSync(handle, stream, true); } /** * Internal method that allows us to prevent looping on self-signed signer keys. * @param handle * @param stream * @param syncSigner * @return * @throws IOException */ protected static boolean localRepoSync(CCNHandle handle, CCNAbstractInputStream stream, boolean syncSigner) throws IOException { boolean result; byte[] digest = stream.getFirstDigest(); // This forces reading if not done already ContentName name = stream.getBaseName(); Long segment = stream.firstSegmentNumber(); Log.info("RepositoryControl.localRepoSync called for name {0}", name); // Request preserving the dereferenced content of the stream first result = internalRepoSync(handle, name, segment, digest, stream.getFirstSegment().fullName()); // Now also deal with each of the links dereferenced to get to the ultimate content LinkObject link = stream.getDereferencedLink(); while (null != link) { // Request preserving current link: note that all of these links have // been dereferenced already to get to the content, and so have been read digest = link.getFirstDigest(); name = link.getVersionedName(); // we need versioned name; link basename may or may not be segment = link.firstSegmentNumber(); if (Log.isLoggable(Level.INFO)) { Log.info("localRepoSync synchronizing link: {0}", link); } if (!internalRepoSync(handle, name, segment, digest, link.getFirstSegment().fullName())) { result = false; } link = link.getDereferencedLink(); } if (syncSigner) { // Finally, we need to ask repository to preserve the signer key (and any links // we need to dereference to get to that (credentials)). We had to retrieve the // key to verify it; it should likely still be in our cache. PublicKeyObject signerKey = handle.keyManager().getPublicKeyObject(stream.publisher(), stream.publisherKeyLocator(), SystemConfiguration.FC_TIMEOUT); if (null != signerKey) { if (!signerKey.available()) { if (Log.isLoggable(Level.INFO)) { Log.info("Signer key {0} not available for syncing.", signerKey.getBaseName()); } } else { if (Log.isLoggable(Level.INFO)) { Log.info("localRepoSync: synchronizing signer key {0}.", signerKey.getVersionedName()); Log.info("localRepoSync: is signer key self-signed? " + signerKey.isSelfSigned()); } // This will traverse any links, and the signer credentials for the lot. // If self-signed, don't sync its signer or we'll loop // We do not change the result if the key was not previously synced; we care // about content. Keys are potentially more often synced, but also more finicky -- // if we're syncing the auto-published keys we can have two copies that differ // only in signing time and signature. localRepoSync(handle, signerKey, !signerKey.isSelfSigned()); } } else { if (Log.isLoggable(Level.INFO)) { Log.info("Cannot retrieve signer key from locator {0}!", stream.publisherKeyLocator()); } } } return result; } public static boolean localRepoSync(CCNHandle handle, CCNNetworkObject<?> obj) throws IOException { return localRepoSync(handle, obj, true); } /** * Internal method that allows us to prevent looping on self-signed signer keys. * @param handle * @param stream * @param syncSigner * @return * @throws IOException */ protected static boolean localRepoSync(CCNHandle handle, CCNNetworkObject<?> obj, boolean syncSigner) throws IOException { boolean result; byte[] digest = obj.getFirstDigest(); // This forces reading if not done already ContentName name = obj.getVersionedName(); Long segment = obj.firstSegmentNumber(); if (Log.isLoggable(Level.INFO)) { Log.info("RepositoryControl.localRepoSync called for net obj name {0}", name); } // Request preserving the dereferenced content of the stream first result = internalRepoSync(handle, name, segment, digest, obj.getFirstSegment().fullName()); // Now also deal with each of the links dereferenced to get to the ultimate content LinkObject link = obj.getDereferencedLink(); while (null != link) { // Request preserving current link: note that all of these links have // been dereferenced already to get to the content, and so have been read digest = link.getFirstDigest(); name = link.getVersionedName(); // we need versioned name; link basename may or may not be segment = link.firstSegmentNumber(); if (!internalRepoSync(handle, name, segment, digest, link.getFirstSegment().fullName())) { result = false; } link = link.getDereferencedLink(); } if (syncSigner) { // Finally, we need to ask repository to preserve the signer key (and any links // we need to dereference to get to that (credentials)). We had to retrieve the // key to verify it; it should likely still be in our cache. KeyLocator keyLocator = obj.getPublisherKeyLocator(); if (obj.getPublisherKeyLocator() == null) { Log.warning("publisher key locator for object we are syncing is null"); } else { if (Log.isLoggable(Level.FINER)) { Log.finer("publisher key locator for object to sync: "+obj.getPublisherKeyLocator()); } if (keyLocator.type() != KeyLocator.KeyLocatorType.NAME) { Log.info("this object contains the key itself... can skip trying to get the key in the repo"); } else { PublicKeyObject signerKey = handle.keyManager().getPublicKeyObject(obj.getContentPublisher(), obj.getPublisherKeyLocator(), SystemConfiguration.FC_TIMEOUT); if (null != signerKey) { if (!signerKey.available()) { if (Log.isLoggable(Level.INFO)) { Log.info("Signer key {0} not available for syncing.", signerKey.getBaseName()); } } else { if (Log.isLoggable(Level.INFO)) { Log.info("localRepoSync: synchronizing signer key {0}.", signerKey.getVersionedName()); Log.info("localRepoSync: is signer key self-signed? " + signerKey.isSelfSigned()); } // This will traverse any links, and the signer credentials for the lot. // If self-signed, don't sync it's signer or we'll loop // We do not change the result if the key was not previously synced; we care // about content. Keys are potentially more often synced, but also more finicky -- // if we're syncing the auto-published keys we can have two copies that differ // only in signing time and signature. localRepoSync(handle, signerKey, !signerKey.isSelfSigned()); } } else { if (Log.isLoggable(Level.INFO)) { Log.info("Cannot retrieve signer key from locator {0}!", obj.getPublisherKeyLocator()); } } } } } return result; } /* * Internal method to generate request for local repository to preserve content stream * @param handle the CCNHandle to use * @param baseName The name of the content up to but not including segment number * @param startingSegmentNumber Initial segment number of the stream * @param firstDigest Digest of the first segment */ static boolean internalRepoSync(CCNHandle handle, ContentName baseName, Long startingSegmentNumber, byte[] firstDigest, ContentName fullName) throws IOException { // UNNECESSARY OVERHEAD: shouldn't have to re-generate full name here, so hand it in. // probably better way than sending in both name and parts. if (syncedObjects.contains(fullName)) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)) { Log.info(Log.FAC_IO, "Sync: skipping already-synced object {0}", fullName); } } // INCORRECT: the protocol is using a nonce. // We do not use a nonce in this protocol, because a cached confirmation is satisfactory, // assuming verification of the repository that published it. ContentName repoCommandName = new ContentName(baseName, new byte[][]{ CommandMarker.COMMAND_MARKER_REPO_CHECKED_START_WRITE.getBytes(), Interest.generateNonce(), SegmentationProfile.getSegmentNumberNameComponent(startingSegmentNumber), firstDigest}); Interest syncInterest = new Interest(repoCommandName); syncInterest.scope(1); // local repositories only if (Log.isLoggable(Log.FAC_IO, Level.INFO)) { Log.info(Log.FAC_IO, "Syncing to repository, interest: {0}", syncInterest); } // Send out Interest ContentObject co = handle.get(syncInterest, SystemConfiguration.FC_TIMEOUT); if (null == co) { if (Log.isLoggable(Log.FAC_IO, Level.INFO)){ Log.info(Log.FAC_IO, "No response from a repository for checked write of " + baseName + " segment " + startingSegmentNumber + " digest " + DataUtils.printHexBytes(firstDigest)); } throw new IOException("No response from a repository for checked write of " + baseName + " segment " + startingSegmentNumber + " digest " + DataUtils.printHexBytes(firstDigest)); } // TODO verify object as published by local repository rather than just signed by anybody if (!handle.defaultVerifier().verify(co)) { // TODO need to bypass unacceptable data to see if something good is out there return false; } if (co.signedInfo().getType() != ContentType.DATA) throw new IOException("Invalid repository response for checked write, type " + co.signedInfo().getType()); RepositoryInfo repoInfo = new RepositoryInfo(); try { repoInfo.decode(co.content()); // At this point, a repo has responded and will deal with our data. Don't need to // sync it again. syncedObjects.add(fullName); if (repoInfo.getType() == RepoInfoType.DATA) { // This type from checked write is confirmation that content already held // TODO improve result handling. Currently we get true if repo has content already, // false if error or repo is storing content but didn't have it already. We don't care // whether repo had it already, all we care is whether it is already or will be synced -- // want to separate errors, repo non-response from "repo will take care of it" responses. return true; } } catch (ContentDecodingException e) { Log.info("ContentDecodingException parsing RepositoryInfo: {0} from content object {1}, skipping.", e.getMessage(), co.name()); } return false; } }
package reply.hacks; import clojure.lang.StringSeq; import java.io.Reader; import java.io.LineNumberReader; import java.io.IOException; import java.util.List; import java.util.LinkedList; public class RawInputTrackingLineNumberingPushbackReader extends CustomizableBufferLineNumberingPushbackReader { private LinkedList<Character> rawInput = new LinkedList<Character>(); public RawInputTrackingLineNumberingPushbackReader(Reader r){ super(new LineNumberReader(r)); } public RawInputTrackingLineNumberingPushbackReader(Reader r, int sz){ super(new LineNumberReader(r, sz), sz); } public List<Character> getRawInput() { return rawInput; } public void clearRawInput() { rawInput = new LinkedList<Character>(); } public int read() throws IOException { int c = super.read(); rawInput.addLast((char) c); return c; } public void unread(int c) throws IOException{ super.unread(c); rawInput.removeLast(); } @SuppressWarnings("unchecked") public String readLine() throws IOException { String line = super.readLine(); if (line != null && line.length() > 0) { rawInput.addAll(StringSeq.create(line)); } return line; } }
package org.helioviewer.gl3d.camera; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; import javax.media.opengl.GL; import javax.media.opengl.glu.GLU; import org.helioviewer.base.logging.Log; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.gl3d.scenegraph.math.GL3DMat4d; import org.helioviewer.gl3d.scenegraph.math.GL3DQuatd; import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d; import org.helioviewer.gl3d.wcs.CoordinateSystem; /** * The GL3DCamera is resposible for the view space transformation. It sets up * the perspective and is generates the view space transformation. This * transformation is in turn influenced by the user interaction. Different * styles of user interaction are supported. These interactions are encapsuled * in {@link GL3DInteraction} objects that can be selected in the main toolbar. * The interactions then change the rotation and translation fields out of which * the resulting cameraTransformation is generated. * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public abstract class GL3DCamera { protected GLU glu = new GLU(); public static final double MAX_DISTANCE = -Constants.SunMeanDistanceToEarth * 1.5; public static final double MIN_DISTANCE = -Constants.SunRadius * 1.2; private double clipNear = Constants.SunRadius / 100.; private double clipFar = Constants.SunRadius * 1000.; private final double fov = 10; private double aspect = 0.0; private double width = 0.0; private double height = 0.0; public int currentMouseX = 0; public int currentMouseY = 0; private final List<GL3DCameraListener> listeners = new ArrayList<GL3DCameraListener>(); // This is the resulting cameraTransformation. All interactions should // modify this matrix private GL3DMat4d cameraTransformation; protected GL3DQuatd rotation; protected GL3DVec3d translation; private final Stack<GL3DCameraAnimation> cameraAnimations = new Stack<GL3DCameraAnimation>(); protected GL3DQuatd currentDragRotation; protected double localrotation; private double differentialRotation; public GL3DCamera(double clipNear, double clipFar) { this(); this.clipNear = clipNear; this.clipFar = clipFar; } public GL3DCamera() { this.cameraTransformation = GL3DMat4d.identity(); this.rotation = GL3DQuatd.createRotation(0.0, new GL3DVec3d(0, 1, 0)); this.translation = new GL3DVec3d(); } public abstract void reset(); /** * This method is called when the camera changes and should copy the * required settings of the preceding camera objects. * * @param precedingCamera */ public void activate(GL3DCamera precedingCamera) { if (precedingCamera != null) { this.rotation = precedingCamera.getRotation().copy(); this.translation = precedingCamera.translation.copy(); this.width = precedingCamera.width; this.height = precedingCamera.height; this.updateCameraTransformation(); // Also set the correct interaction if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getRotateInteraction())) { this.setCurrentInteraction(this.getRotateInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getPanInteraction())) { this.setCurrentInteraction(this.getPanInteraction()); } else if (precedingCamera.getCurrentInteraction().equals(precedingCamera.getZoomInteraction())) { this.setCurrentInteraction(this.getZoomInteraction()); } } else { Log.debug("GL3DCamera: No Preceding Camera, resetting Camera"); this.reset(); } } protected void setZTranslation(double z) { this.translation.z = Math.min(MIN_DISTANCE, Math.max(MAX_DISTANCE, z)); } protected void addPanning(double x, double y) { setPanning(this.translation.x + x, this.translation.y + y); } public void setPanning(double x, double y) { this.translation.x = x; this.translation.y = y; } public GL3DVec3d getTranslation() { return this.translation; } public GL3DMat4d getCameraTransformation() { return this.cameraTransformation; } public double getZTranslation() { return getTranslation().z; } public GL3DQuatd getRotation() { return this.rotation; } public void setRotation(GL3DQuatd rotation) { this.rotation = rotation; } public void deactivate() { this.cameraAnimations.clear(); } public void applyPerspective(GL3DState state) { GL gl = state.gl; int viewport[] = new int[4]; gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0); this.width = viewport[2]; this.height = viewport[3]; this.aspect = width / height; gl.glMatrixMode(GL.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); glu.gluPerspective(this.fov, this.aspect, this.clipNear, this.clipFar); gl.glMatrixMode(GL.GL_MODELVIEW); } public void resumePerspective(GL3DState state) { GL gl = state.gl; gl.glMatrixMode(GL.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL.GL_MODELVIEW); } public void updateCameraTransformation() { this.updateCameraTransformation(true); } public void updateCameraTransformation(GL3DMat4d transformation) { this.cameraTransformation = transformation; // fireCameraMoved(); } /** * Updates the camera transformation by applying the rotation and * translation information. */ public void updateCameraTransformation(boolean fireEvent) { cameraTransformation = GL3DMat4d.identity(); cameraTransformation.translate(this.translation); cameraTransformation.multiply(this.rotation.toMatrix()); if (fireEvent) { fireCameraMoved(); } } public void applyCamera(GL3DState state) { for (Iterator<GL3DCameraAnimation> iter = this.cameraAnimations.iterator(); iter.hasNext();) { GL3DCameraAnimation animation = iter.next(); if (!animation.isFinished()) { animation.animate(this); } else { iter.remove(); } } state.multiplyMV(cameraTransformation); } public void addCameraAnimation(GL3DCameraAnimation animation) { for (Iterator<GL3DCameraAnimation> iter = this.cameraAnimations.iterator(); iter.hasNext();) { GL3DCameraAnimation ani = iter.next(); if (!ani.isFinished() && ani.getClass().isInstance(animation)) { ani.updateWithAnimation(animation); return; } } this.cameraAnimations.add(animation); } public abstract GL3DMat4d getVM(); public abstract double getDistanceToSunSurface(); public abstract GL3DInteraction getPanInteraction(); public abstract GL3DInteraction getRotateInteraction(); public abstract GL3DInteraction getZoomInteraction(); public abstract String getName(); public void drawCamera(GL3DState state) { getCurrentInteraction().drawInteractionFeedback(state, this); } public abstract GL3DInteraction getCurrentInteraction(); public abstract void setCurrentInteraction(GL3DInteraction currentInteraction); public double getFOV() { return this.fov; } public double getClipNear() { return clipNear; } public double getClipFar() { return clipFar; } public double getAspect() { return aspect; } public double getWidth() { return width; } public double getHeight() { return height; } @Override public String toString() { return getName(); } public void addCameraListener(GL3DCameraListener listener) { this.listeners.add(listener); } public void removeCameraListener(GL3DCameraListener listener) { this.listeners.remove(listener); } protected void fireCameraMoved() { for (GL3DCameraListener l : this.listeners) { l.cameraMoved(this); } } protected void fireCameraMoving() { for (GL3DCameraListener l : this.listeners) { l.cameraMoving(this); } } public abstract CoordinateSystem getViewSpaceCoordinateSystem(); public boolean isAnimating() { return !this.cameraAnimations.isEmpty(); } public double getDifferentialRotation() { return differentialRotation; } public void setDifferentialRotation(double differentialRotation) { this.differentialRotation = differentialRotation; } public void updateRotation(long dateMillis) { } }
package jsettlers.logic.map.newGrid; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.List; import java.util.Random; import jsettlers.common.Color; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.buildings.IBuilding; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.map.IGraphicsBackgroundListener; import jsettlers.common.map.IGraphicsGrid; import jsettlers.common.map.shapes.FreeMapArea; import jsettlers.common.map.shapes.IMapArea; import jsettlers.common.map.shapes.MapNeighboursArea; import jsettlers.common.map.shapes.MapShapeFilter; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.mapobject.IMapObject; import jsettlers.common.material.EMaterialType; import jsettlers.common.material.ESearchType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.EMovableType; import jsettlers.common.movable.IMovable; import jsettlers.common.position.ISPosition2D; import jsettlers.common.position.RelativePoint; import jsettlers.common.position.ShortPoint2D; import jsettlers.input.IGuiInputGrid; import jsettlers.logic.algorithms.borders.BordersThread; import jsettlers.logic.algorithms.borders.IBordersThreadGrid; import jsettlers.logic.algorithms.construction.ConstructMarksThread; import jsettlers.logic.algorithms.construction.IConstructionMarkableMap; import jsettlers.logic.algorithms.fogofwar.FogOfWar; import jsettlers.logic.algorithms.fogofwar.IFogOfWarGrid; import jsettlers.logic.algorithms.landmarks.ILandmarksThreadMap; import jsettlers.logic.algorithms.landmarks.LandmarksCorrectingThread; import jsettlers.logic.algorithms.path.IPathCalculateable; import jsettlers.logic.algorithms.path.area.IInAreaFinderMap; import jsettlers.logic.algorithms.path.area.InAreaFinder; import jsettlers.logic.algorithms.path.astar.HexAStar; import jsettlers.logic.algorithms.path.astar.IAStarPathMap; import jsettlers.logic.algorithms.path.dijkstra.DijkstraAlgorithm; import jsettlers.logic.algorithms.path.dijkstra.IDijkstraPathMap; import jsettlers.logic.buildings.Building; import jsettlers.logic.buildings.IBuildingsGrid; import jsettlers.logic.buildings.military.Barrack; import jsettlers.logic.buildings.workers.WorkerBuilding; import jsettlers.logic.constants.Constants; import jsettlers.logic.map.newGrid.flags.FlagsGrid; import jsettlers.logic.map.newGrid.interfaces.AbstractHexMapObject; import jsettlers.logic.map.newGrid.interfaces.IHexMovable; import jsettlers.logic.map.newGrid.landscape.LandscapeGrid; import jsettlers.logic.map.newGrid.movable.MovableGrid; import jsettlers.logic.map.newGrid.objects.IMapObjectsManagerGrid; import jsettlers.logic.map.newGrid.objects.MapObjectsManager; import jsettlers.logic.map.newGrid.objects.ObjectsGrid; import jsettlers.logic.map.newGrid.partition.IPartitionableGrid; import jsettlers.logic.map.newGrid.partition.PartitionsGrid; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableBearer; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableBricklayer; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableDigger; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableWorker; import jsettlers.logic.map.newGrid.partition.manager.manageables.interfaces.IDiggerRequester; import jsettlers.logic.map.newGrid.partition.manager.manageables.interfaces.IMaterialRequester; import jsettlers.logic.map.random.RandomMapEvaluator; import jsettlers.logic.map.random.RandomMapFile; import jsettlers.logic.map.random.grid.BuildingObject; import jsettlers.logic.map.random.grid.MapGrid; import jsettlers.logic.map.random.grid.MapObject; import jsettlers.logic.map.random.grid.MapStoneObject; import jsettlers.logic.map.random.grid.MapTreeObject; import jsettlers.logic.map.random.grid.MovableObject; import jsettlers.logic.map.random.grid.StackObject; import jsettlers.logic.movable.IMovableGrid; import jsettlers.logic.movable.Movable; import jsettlers.logic.stack.IRequestsStackGrid; /** * This is the main grid offering an interface for interacting with the grid. * * @author Andreas Eberle * */ public class MainGrid implements Serializable { private static final long serialVersionUID = 3824511313693431423L; final short width; final short height; final LandscapeGrid landscapeGrid; final ObjectsGrid objectsGrid; final PartitionsGrid partitionsGrid; final MovableGrid movableGrid; final FlagsGrid flagsGrid; transient Color[][] debugColors; final MovablePathfinderGrid movablePathfinderGrid; final MapObjectsManager mapObjectsManager; final BuildingsGrid buildingsGrid; private final FogOfWar fogOfWar; transient IGraphicsGrid graphicsGrid; transient LandmarksCorrectingThread landmarksCorrectionThread; transient ConstructionMarksGrid constructionMarksGrid; transient ConstructMarksThread constructionMarksCalculator; transient BordersThread bordersThread; transient IGuiInputGrid guiInputGrid; public MainGrid(short width, short height) { this.width = width; this.height = height; this.movablePathfinderGrid = new MovablePathfinderGrid(); this.mapObjectsManager = new MapObjectsManager(new MapObjectsManagerGrid()); this.landscapeGrid = new LandscapeGrid(width, height); this.objectsGrid = new ObjectsGrid(width, height); this.movableGrid = new MovableGrid(width, height); this.flagsGrid = new FlagsGrid(width, height); this.partitionsGrid = new PartitionsGrid(width, height, new PartitionableGrid(), movablePathfinderGrid); this.buildingsGrid = new BuildingsGrid(); this.fogOfWar = new FogOfWar(width, height); // TODO @Andreas implement new interface for fog of war initAdditionalGrids(); } private void initAdditionalGrids() { this.graphicsGrid = new GraphicsGrid(); this.landmarksCorrectionThread = new LandmarksCorrectingThread(new LandmarksGrid()); this.constructionMarksGrid = new ConstructionMarksGrid(); this.constructionMarksCalculator = new ConstructMarksThread(constructionMarksGrid, (byte) 0); this.bordersThread = new BordersThread(new BordersThreadGrid()); this.guiInputGrid = new GUIInputGrid(); this.debugColors = new Color[width][height]; this.fogOfWar.startThread(new FogOfWarGrid()); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); initAdditionalGrids(); } private MainGrid(MapGrid mapGrid) { this((short) mapGrid.getWidth(), (short) mapGrid.getHeight()); for (short y = 0; y < height; y++) { for (short x = 0; x < width; x++) { landscapeGrid.setLandscapeTypeAt(x, y, mapGrid.getLandscape(x, y)); landscapeGrid.setHeightAt(x, y, mapGrid.getLandscapeHeight(x, y)); } } // tow passes, we might need the base grid tiles to add blocking, ... status for (short y = 0; y < height; y++) { for (short x = 0; x < width; x++) { MapObject object = mapGrid.getMapObject(x, y); if (object != null) { addMapObject(x, y, object); } } } System.out.println("grid filled"); } public static MainGrid createForDebugging() { MainGrid grid = new MainGrid((short) 200, (short) 100); for (short x = 0; x < grid.width; x++) { for (short y = 0; y < grid.height; y++) { grid.landscapeGrid.setLandscapeTypeAt(x, y, ELandscapeType.GRASS); grid.landscapeGrid.setHeightAt(x, y, (byte) 0); } } Building tower = Building.getBuilding(EBuildingType.TOWER, (byte) 0); tower.appearAt(grid.buildingsGrid, new ShortPoint2D(55, 50)); tower = Building.getBuilding(EBuildingType.TOWER, (byte) 0); tower.appearAt(grid.buildingsGrid, new ShortPoint2D(145, 50)); grid.placeStack(new ShortPoint2D(30, 50), EMaterialType.PLANK, 8); grid.placeStack(new ShortPoint2D(32, 50), EMaterialType.PLANK, 8); grid.placeStack(new ShortPoint2D(34, 50), EMaterialType.PLANK, 8); grid.placeStack(new ShortPoint2D(36, 50), EMaterialType.PLANK, 8); grid.placeStack(new ShortPoint2D(30, 40), EMaterialType.STONE, 8); grid.placeStack(new ShortPoint2D(32, 40), EMaterialType.STONE, 8); grid.placeStack(new ShortPoint2D(34, 40), EMaterialType.STONE, 8); grid.placeStack(new ShortPoint2D(36, 40), EMaterialType.STONE, 8); grid.placeStack(new ShortPoint2D(34, 30), EMaterialType.HAMMER, 1); grid.placeStack(new ShortPoint2D(36, 30), EMaterialType.BLADE, 1); grid.placeStack(new ShortPoint2D(38, 30), EMaterialType.AXE, 1); grid.placeStack(new ShortPoint2D(40, 30), EMaterialType.SAW, 1); for (int i = 0; i < 10; i++) { grid.createNewMovableAt(new ShortPoint2D(60 + 2 * i, 50), EMovableType.BEARER, (byte) 0); } grid.createNewMovableAt(new ShortPoint2D(50, 50), EMovableType.PIONEER, (byte) 0); grid.createNewMovableAt(new ShortPoint2D(60, 60), EMovableType.SWORDSMAN_L3, (byte) 0); return grid; } public static MainGrid create(String filename, byte players, Random random) { RandomMapFile file = RandomMapFile.getByName(filename); RandomMapEvaluator evaluator = new RandomMapEvaluator(file.getInstructions(), players); evaluator.createMap(random); MapGrid mapGrid = evaluator.getGrid(); System.out.println("Generated random map"); return new MainGrid(mapGrid); } private void addMapObject(short x, short y, MapObject object) { ISPosition2D pos = new ShortPoint2D(x, y); if (object instanceof MapTreeObject) { if (isInBounds(x, y) && movablePathfinderGrid.isTreePlantable(x, y)) { mapObjectsManager.plantAdultTree(pos); } } else if (object instanceof MapStoneObject) { mapObjectsManager.addStone(pos, ((MapStoneObject) object).getCapacity()); } else if (object instanceof StackObject) { placeStack(pos, ((StackObject) object).getType(), ((StackObject) object).getCount()); } else if (object instanceof BuildingObject) { Building building = Building.getBuilding(((BuildingObject) object).getType(), ((BuildingObject) object).getPlayer()); building.appearAt(buildingsGrid, pos); } else if (object instanceof MovableObject) { createNewMovableAt(pos, ((MovableObject) object).getType(), ((MovableObject) object).getPlayer()); } } private void placeStack(ISPosition2D pos, EMaterialType materialType, int count) { for (int i = 0; i < count; i++) { movablePathfinderGrid.pushMaterial(pos, materialType, true); } } public IGraphicsGrid getGraphicsGrid() { return graphicsGrid; } public IGuiInputGrid getGuiInputGrid() { return guiInputGrid; } protected final boolean isInBounds(short x, short y) { return x >= 0 && x < width && y >= 0 && y < height; } private void changePlayerAt(ISPosition2D position, byte player) { partitionsGrid.changePlayerAt(position.getX(), position.getY(), player); bordersThread.checkPosition(position); landmarksCorrectionThread.addLandmarkedPosition(position); } public void createNewMovableAt(ISPosition2D pos, EMovableType type, byte player) { buildingsGrid.placeNewMovable(pos, new Movable(movablePathfinderGrid, pos, type, player)); } protected boolean isLandscapeBlocking(short x, short y) { ELandscapeType landscapeType = landscapeGrid.getLandscapeTypeAt(x, y); return landscapeType == ELandscapeType.WATER || landscapeType == ELandscapeType.SNOW; } class PathfinderGrid implements IAStarPathMap, IDijkstraPathMap, IInAreaFinderMap, Serializable { private static final long serialVersionUID = -2775530442375843213L; @Override public short getHeight() { return height; } @Override public short getWidth() { return width; } @Override public boolean isBlocked(IPathCalculateable requester, short x, short y) { return flagsGrid.isBlocked(x, y) || isLandscapeBlocking(x, y) || (requester.needsPlayersGround() && requester.getPlayer() != partitionsGrid.getPlayerAt(x, y)); } @Override public float getHeuristicCost(short sx, short sy, short tx, short ty) { float dx = (short) Math.abs(sx - tx); float dy = (short) Math.abs(sy - ty); return (dx + dy) * Constants.TILE_HEURISTIC_DIST; } @Override public float getCost(short sx, short sy, short tx, short ty) { return Constants.TILE_PATHFINDER_COST * (flagsGrid.isProtected(sx, sy) ? 3.5f : 1); } @Override public void markAsOpen(short x, short y) { debugColors[x][y] = Color.BLUE; } @Override public void markAsClosed(short x, short y) { debugColors[x][y] = Color.RED; } @Override public void setDijkstraSearched(short x, short y) { markAsOpen(x, y); } @Override public boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public boolean fitsSearchType(short x, short y, ESearchType searchType, IPathCalculateable pathCalculable) { switch (searchType) { case FOREIGN_GROUND: return !flagsGrid.isBlocked(x, y) && !hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y) && !partitionsGrid.isEnforcedByTower(x, y); case CUTTABLE_TREE: return isInBounds((short) (x - 1), (short) (y - 1)) && objectsGrid.hasCuttableObject((short) (x - 1), (short) (y - 1), EMapObjectType.TREE_ADULT) && hasSamePlayer((short) (x - 1), (short) (y - 1), pathCalculable) && !isMarked(x, y); case PLANTABLE_TREE: return y < height - 1 && isTreePlantable(x, (short) (y + 1)) && !hasProtectedNeighbor(x, (short) (y + 1)) && hasSamePlayer(x, (short) (y + 1), pathCalculable) && !isMarked(x, y); case PLANTABLE_CORN: return isCornPlantable(x, y) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y) && !flagsGrid.isProtected(x, y); case CUTTABLE_CORN: return isCornCuttable(x, y) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y); case CUTTABLE_STONE: return y < height - 1 && x < width - 2 && objectsGrid.hasCuttableObject((short) (x - 2), (short) (y - 1), EMapObjectType.STONE) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y); case ENEMY: IMovable movable = movableGrid.getMovableAt(x, y); return movable != null && movable.getPlayer() != pathCalculable.getPlayer(); case RIVER: return isRiver(x, y) && hasSamePlayer(x, y, pathCalculable) && !isMarked(x, y); case FISHABLE: return hasSamePlayer(x, y, pathCalculable) && hasNeighbourLandscape(x, y, ELandscapeType.WATER); case NON_BLOCKED_OR_PROTECTED: return !(flagsGrid.isProtected(x, y) || flagsGrid.isBlocked(x, y) || isLandscapeBlocking(x, y)) && (!pathCalculable.needsPlayersGround() || hasSamePlayer(x, y, pathCalculable)) && movableGrid.getMovableAt(x, y) == null; default: System.err.println("can't handle search type in fitsSearchType(): " + searchType); return false; } } private boolean isMarked(short x, short y) { return flagsGrid.isMarked(x, y); } private boolean hasProtectedNeighbor(short x, short y) { for (EDirection currDir : EDirection.values()) { if (flagsGrid.isProtected(currDir.getNextTileX(x), currDir.getNextTileY(y))) return true; } return false; } private boolean hasNeighbourLandscape(short x, short y, ELandscapeType landscape) { for (ISPosition2D pos : new MapNeighboursArea(new ShortPoint2D(x, y))) { short currX = pos.getX(); short currY = pos.getY(); if (isInBounds(currX, currY) && landscapeGrid.getLandscapeTypeAt(currX, currY) == landscape) { return true; } } return false; } private boolean hasSamePlayer(short x, short y, IPathCalculateable requester) { return partitionsGrid.getPlayerAt(x, y) == requester.getPlayer(); } private boolean isRiver(short x, short y) { ELandscapeType type = landscapeGrid.getLandscapeTypeAt(x, y); return type == ELandscapeType.RIVER1 || type == ELandscapeType.RIVER2 || type == ELandscapeType.RIVER3 || type == ELandscapeType.RIVER4; } boolean isTreePlantable(short x, short y) { return landscapeGrid.getLandscapeTypeAt(x, y) == ELandscapeType.GRASS && !flagsGrid.isBlocked(x, y) && !hasBlockedNeighbor(x, y); } private boolean hasBlockedNeighbor(short x, short y) { for (EDirection currDir : EDirection.values()) { short currX = currDir.getNextTileX(x); short currY = currDir.getNextTileY(y); if (!isInBounds(currX, currY) || flagsGrid.isBlocked(currX, currY)) { return true; } } return false; } private boolean isCornPlantable(short x, short y) { ELandscapeType landscapeType = landscapeGrid.getLandscapeTypeAt(x, y); return (landscapeType == ELandscapeType.GRASS || landscapeType == ELandscapeType.EARTH) && !flagsGrid.isProtected(x, y) && !hasProtectedNeighbor(x, y) && !objectsGrid.hasMapObjectType(x, y, EMapObjectType.CORN_GROWING) && !objectsGrid.hasMapObjectType(x, y, EMapObjectType.CORN_ADULT) && !objectsGrid.hasNeighborObjectType(x, y, EMapObjectType.CORN_ADULT) && !objectsGrid.hasNeighborObjectType(x, y, EMapObjectType.CORN_GROWING); } private boolean isCornCuttable(short x, short y) { return objectsGrid.hasCuttableObject(x, y, EMapObjectType.CORN_ADULT); } } class GraphicsGrid implements IGraphicsGrid { @Override public short getHeight() { return height; } @Override public short getWidth() { return width; } @Override public IMovable getMovableAt(int x, int y) { return movableGrid.getMovableAt((short) x, (short) y); } @Override public IMapObject getMapObjectsAt(int x, int y) { return objectsGrid.getObjectsAt((short) x, (short) y); } @Override public byte getHeightAt(int x, int y) { return landscapeGrid.getHeightAt((short) x, (short) y); } @Override public ELandscapeType getLandscapeTypeAt(int x, int y) { return landscapeGrid.getLandscapeTypeAt((short) x, (short) y); } @Override public Color getDebugColorAt(int x, int y) { // short value = (short) (partitionsGrid.getPartitionAt((short) x, (short) y) + 1); // return new Color((value % 3) * 0.33f, ((value / 3) % 3) * 0.33f, ((value / 9) % 3) * 0.33f, 1); // return debugColors[x][y]; return flagsGrid.isBlocked((short) x, (short) y) ? new Color(0, 0, 0, 1) : (flagsGrid.isProtected((short) x, (short) y) ? new Color(0, 0, 1, 1) : null); } @Override public boolean isBorder(int x, int y) { return partitionsGrid.isBorderAt((short) x, (short) y); } @Override public byte getPlayerAt(int x, int y) { return partitionsGrid.getPlayerAt((short) x, (short) y); } @Override public byte getVisibleStatus(int x, int y) { return fogOfWar.getVisibleStatus(x, y); } @Override public boolean isFogOfWarVisible(int x, int y) { return fogOfWar.isVisible(x, y); } @Override public void setBackgroundListener(IGraphicsBackgroundListener backgroundListener) { landscapeGrid.setBackgroundListener(backgroundListener); } } class MapObjectsManagerGrid implements IMapObjectsManagerGrid { private static final long serialVersionUID = 6223899915568781576L; @Override public void setLandscape(short x, short y, ELandscapeType landscapeType) { landscapeGrid.setLandscapeTypeAt(x, y, landscapeType); } @Override public void setBlocked(short x, short y, boolean blocked) { flagsGrid.setBlockedAndProtected(x, y, blocked); } @Override public AbstractHexMapObject removeMapObjectType(short x, short y, EMapObjectType mapObjectType) { return objectsGrid.removeMapObjectType(x, y, mapObjectType); } @Override public boolean removeMapObject(short x, short y, AbstractHexMapObject mapObject) { return objectsGrid.removeMapObject(x, y, mapObject); } @Override public boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y); } @Override public AbstractHexMapObject getMapObject(short x, short y, EMapObjectType mapObjectType) { return objectsGrid.getMapObjectAt(x, y, mapObjectType); } @Override public void addMapObject(short x, short y, AbstractHexMapObject mapObject) { objectsGrid.addMapObjectAt(x, y, mapObject); } @Override public short getWidth() { return width; } @Override public short getHeight() { return height; } @Override public boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public void setProtected(short x, short y, boolean protect) { flagsGrid.setProtected(x, y, protect); } } class LandmarksGrid implements ILandmarksThreadMap { @Override public boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y); } @Override public boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } @Override public short getPartitionAt(short x, short y) { return partitionsGrid.getPartitionAt(x, y); } @Override public void setPartitionAndPlayerAt(short x, short y, short partition) { partitionsGrid.setPartitionAndPlayerAt(x, y, partition); bordersThread.checkPosition(new ShortPoint2D(x, y)); } } class ConstructionMarksGrid implements IConstructionMarkableMap { @Override public void setConstructMarking(ISPosition2D pos, byte value) { mapObjectsManager.setConstructionMarking(pos, value); } @Override public short getWidth() { return width; } @Override public short getHeight() { return height; } @Override public byte getHeightAt(short x, short y) { return landscapeGrid.getHeightAt(x, y); } @Override public boolean canConstructAt(short x, short y, EBuildingType type, byte player) { ELandscapeType[] landscapes = type.getGroundtypes(); for (RelativePoint curr : type.getProtectedTiles()) { short currX = curr.calculateX(x); short currY = curr.calculateY(y); if (!MainGrid.this.isInBounds(currX, currY) || flagsGrid.isProtected(currX, currY) || partitionsGrid.getPlayerAt(currX, currY) != player || !isAllowedLandscape(currX, currY, landscapes)) { return false; } } return true; } private boolean isAllowedLandscape(short x, short y, ELandscapeType[] landscapes) { ELandscapeType landscapeAt = landscapeGrid.getLandscapeTypeAt(x, y); for (byte i = 0; i < landscapes.length; i++) { if (landscapeAt == landscapes[i]) { return true; } } return false; } } class MovablePathfinderGrid extends PathfinderGrid implements IMovableGrid, Serializable { private static final long serialVersionUID = 4006228724969442801L; transient private HexAStar aStar; transient private DijkstraAlgorithm dijkstra; transient private InAreaFinder inAreaFinder; public MovablePathfinderGrid() { initPathfinders(); } private final void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); initPathfinders(); } private final void initPathfinders() { aStar = new HexAStar(this); dijkstra = new DijkstraAlgorithm(this, aStar); inAreaFinder = new InAreaFinder(this); } @Override public final void movableLeft(ISPosition2D position, IHexMovable movable) { movableGrid.movableLeft(position, movable); } @Override public final void movableEntered(ISPosition2D position, IHexMovable movable) { movableGrid.movableEntered(position, movable); } @Override public final MapObjectsManager getMapObjectsManager() { return mapObjectsManager; } @Override public final IHexMovable getMovable(ISPosition2D position) { return movableGrid.getMovableAt(position.getX(), position.getY()); } @Override public final boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y) || isLandscapeBlocking(x, y); } @Override public final boolean canPush(ISPosition2D position) { return mapObjectsManager.canPush(position); } @Override public final boolean pushMaterial(ISPosition2D position, EMaterialType materialType, boolean offer) { if (mapObjectsManager.pushMaterial(position, materialType)) { if (offer) { partitionsGrid.pushMaterial(position, materialType); } return true; } else return false; } @Override public final boolean canPop(ISPosition2D position, EMaterialType material) { return mapObjectsManager.canPop(position, material); } @Override public final boolean popMaterial(ISPosition2D position, EMaterialType materialType) { if (mapObjectsManager.popMaterial(position, materialType)) { return true; } else return false; } @Override public final ELandscapeType getLandscapeTypeAt(ISPosition2D position) { return landscapeGrid.getLandscapeTypeAt(position.getX(), position.getY()); } @Override public final byte getHeightAt(ISPosition2D position) { return landscapeGrid.getHeightAt(position.getX(), position.getY()); } @Override public final void changeHeightAt(ISPosition2D position, byte delta) { landscapeGrid.changeHeightAt(position.getX(), position.getY(), delta); } @Override public final void setMarked(ISPosition2D position, boolean marked) { flagsGrid.setMarked(position.getX(), position.getY(), marked); } @Override public final boolean isMarked(ISPosition2D position) { return flagsGrid.isMarked(position.getX(), position.getY()); } @Override public final boolean isInBounds(ISPosition2D position) { return isInBounds(position.getX(), position.getY()); } @Override public final byte getPlayerAt(ISPosition2D position) { return partitionsGrid.getPlayerAt(position); } @Override public final void changePlayerAt(ISPosition2D position, byte player) { MainGrid.this.changePlayerAt(position, player); } @Override public final boolean executeSearchType(ISPosition2D position, ESearchType searchType) { return mapObjectsManager.executeSearchType(position, searchType); } @Override public final HexAStar getAStar() { return aStar; } @Override public final DijkstraAlgorithm getDijkstra() { return dijkstra; } @Override public final InAreaFinder getInAreaFinder() { return inAreaFinder; } @Override public final boolean fitsSearchType(ISPosition2D position, ESearchType searchType, IPathCalculateable pathCalculateable) { return super.fitsSearchType(position.getX(), position.getY(), searchType, pathCalculateable); } @Override public final void addJobless(IManageableBearer manageable) { partitionsGrid.addJobless(manageable); } @Override public final void addJobless(IManageableWorker worker) { partitionsGrid.addJobless(worker); } @Override public final void addJobless(IManageableBricklayer bricklayer) { partitionsGrid.addJobless(bricklayer); } @Override public final void addJobless(IManageableDigger digger) { partitionsGrid.addJobless(digger); } @Override public final void changeLandscapeAt(ISPosition2D pos, ELandscapeType type) { landscapeGrid.setLandscapeTypeAt(pos.getX(), pos.getY(), type); } @Override public final void placeSmoke(ISPosition2D pos, boolean place) { if (place) { mapObjectsManager.addSimpleMapObject(pos, EMapObjectType.SMOKE, false, (byte) 0); } else { mapObjectsManager.removeMapObjectType(pos, EMapObjectType.SMOKE); } } @Override public final boolean isProtected(short x, short y) { return flagsGrid.isProtected(x, y); } @Override public final void placePig(ISPosition2D pos, boolean place) { mapObjectsManager.placePig(pos, place); } @Override public final boolean isPigThere(ISPosition2D pos) { return mapObjectsManager.isPigThere(pos); } @Override public final boolean isPigAdult(ISPosition2D pos) { return mapObjectsManager.isPigAdult(pos); } @Override public final boolean isEnforcedByTower(ISPosition2D pos) { return partitionsGrid.isEnforcedByTower(pos.getX(), pos.getY()); } } class BordersThreadGrid implements IBordersThreadGrid { @Override public final byte getPlayer(short x, short y) { return partitionsGrid.getPlayerAt(x, y); } @Override public final void setBorder(short x, short y, boolean isBorder) { partitionsGrid.setBorderAt(x, y, isBorder); } @Override public final boolean isInBounds(short x, short y) { return MainGrid.this.isInBounds(x, y); } } class BuildingsGrid implements IBuildingsGrid, Serializable { private static final long serialVersionUID = -5567034251907577276L; private final RequestStackGrid requestStackGrid = new RequestStackGrid(); @Override public final byte getHeightAt(ISPosition2D position) { return landscapeGrid.getHeightAt(position.getX(), position.getY()); } @Override public final void pushMaterialsTo(ISPosition2D position, EMaterialType type, byte numberOf) { for (int i = 0; i < numberOf; i++) { movablePathfinderGrid.pushMaterial(position, type, true); } } @Override public final boolean setBuilding(ISPosition2D position, Building newBuilding) { if (MainGrid.this.isInBounds(position.getX(), position.getY())) { FreeMapArea area = new FreeMapArea(position, newBuilding.getBuildingType().getProtectedTiles()); if (canConstructAt(area)) { setProtectedState(area, true); mapObjectsManager.addBuildingTo(position, newBuilding); return true; } else { return false; } } else { return false; } } private final void setProtectedState(FreeMapArea area, boolean setProtected) { for (ISPosition2D curr : area) { if (MainGrid.this.isInBounds(curr.getX(), curr.getY())) flagsGrid.setProtected(curr.getX(), curr.getY(), setProtected); } } private final boolean canConstructAt(FreeMapArea area) { boolean isFree = true; for (ISPosition2D curr : area) { short x = curr.getX(); short y = curr.getY(); if (!isInBounds(x, y) || flagsGrid.isProtected(x, y) || flagsGrid.isBlocked(x, y)) { isFree = false; } } return isFree; } @Override public final void removeBuildingAt(ISPosition2D pos) { IBuilding building = (IBuilding) objectsGrid.getMapObjectAt(pos.getX(), pos.getY(), EMapObjectType.BUILDING); mapObjectsManager.removeMapObjectType(pos, EMapObjectType.BUILDING); FreeMapArea area = new FreeMapArea(pos, building.getBuildingType().getProtectedTiles()); for (ISPosition2D curr : area) { if (isInBounds(curr.getX(), curr.getY())) { flagsGrid.setBlockedAndProtected(curr.getX(), curr.getY(), false); } } } @Override public final void occupyArea(MapShapeFilter toBeOccupied, ISPosition2D occupiersPosition, byte player) { List<ISPosition2D> occupiedPositions = partitionsGrid.occupyArea(toBeOccupied, occupiersPosition, player); bordersThread.checkPositions(occupiedPositions); landmarksCorrectionThread.addLandmarkedPositions(occupiedPositions); } @Override public final void freeOccupiedArea(MapShapeFilter occupied, ISPosition2D pos) { List<ISPosition2D> totallyFreed = partitionsGrid.freeOccupiedArea(occupied, pos); if (!totallyFreed.isEmpty()) { // FIXME check for towers that would already occupy this location } } @Override public final void setBlocked(FreeMapArea area, boolean blocked) { for (ISPosition2D curr : area) { if (MainGrid.this.isInBounds(curr.getX(), curr.getY())) flagsGrid.setBlockedAndProtected(curr.getX(), curr.getY(), blocked); } } @Override public final short getWidth() { return width; } @Override public final short getHeight() { return height; } @Override public final IHexMovable getMovable(ISPosition2D position) { return movableGrid.getMovableAt(position.getX(), position.getY()); } @Override public final void placeNewMovable(ISPosition2D position, IHexMovable movable) { movableGrid.movableEntered(position, movable); } @Override public final MapObjectsManager getMapObjectsManager() { return mapObjectsManager; } @Override public final IMovableGrid getMovableGrid() { return movablePathfinderGrid; } @Override public final void requestDiggers(IDiggerRequester requester, byte amount) { partitionsGrid.requestDiggers(requester, amount); } @Override public final void requestBricklayer(Building building, ShortPoint2D bricklayerTargetPos, EDirection direction) { partitionsGrid.requestBricklayer(building, bricklayerTargetPos, direction); } @Override public final IRequestsStackGrid getRequestStackGrid() { return requestStackGrid; } @Override public final void requestBuildingWorker(EMovableType workerType, WorkerBuilding workerBuilding) { partitionsGrid.requestBuildingWorker(workerType, workerBuilding); } @Override public final void requestSoilderable(Barrack barrack) { partitionsGrid.requestSoilderable(barrack); } private class RequestStackGrid implements IRequestsStackGrid, Serializable { private static final long serialVersionUID = 1278397366408051067L; @Override public final void request(IMaterialRequester requester, EMaterialType materialType, byte priority) { partitionsGrid.request(requester, materialType, priority); } @Override public final boolean hasMaterial(ISPosition2D position, EMaterialType materialType) { return mapObjectsManager.canPop(position, materialType); } @Override public final void popMaterial(ISPosition2D position, EMaterialType materialType) { mapObjectsManager.popMaterial(position, materialType); } @Override public final byte getStackSize(ISPosition2D position, EMaterialType materialType) { return mapObjectsManager.getStackSize(position, materialType); } @Override public final void releaseRequestsAt(ISPosition2D position, EMaterialType materialType) { partitionsGrid.releaseRequestsAt(position, materialType); byte stackSize = mapObjectsManager.getStackSize(position, materialType); for (byte i = 0; i < stackSize; i++) { partitionsGrid.pushMaterial(position, materialType); } } } } class GUIInputGrid implements IGuiInputGrid { @Override public final IHexMovable getMovable(short x, short y) { return movableGrid.getMovableAt(x, y); } @Override public final short getWidth() { return width; } @Override public final short getHeight() { return height; } @Override public final IBuilding getBuildingAt(short x, short y) { return (IBuilding) objectsGrid.getMapObjectAt(x, y, EMapObjectType.BUILDING); } @Override public final boolean isInBounds(ISPosition2D position) { return MainGrid.this.isInBounds(position.getX(), position.getY()); } @Override public final IBuildingsGrid getBuildingsGrid() { return buildingsGrid; } @Override public final byte getPlayerAt(ISPosition2D position) { return partitionsGrid.getPlayerAt(position); } @Override public final void setBuildingType(EBuildingType buildingType) { constructionMarksCalculator.setBuildingType(buildingType); } @Override public final void setScreen(IMapArea screenArea) { constructionMarksCalculator.setScreen(screenArea); } @Override public final void resetDebugColors() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { debugColors[x][y] = null; } } } @Override public final ISPosition2D getConstructablePositionAround(ISPosition2D pos, EBuildingType type) { byte player = partitionsGrid.getPlayerAt(pos); if (constructionMarksGrid.canConstructAt(pos.getX(), pos.getY(), type, player)) { return pos; } else { for (ISPosition2D neighbour : new MapNeighboursArea(pos)) { if (constructionMarksGrid.canConstructAt(neighbour.getX(), neighbour.getY(), type, player)) { return neighbour; } } return null; } } @Override public final void save() throws FileNotFoundException, IOException { GameSerializer serializer = new GameSerializer(); serializer.save(MainGrid.this); } } class PartitionableGrid implements IPartitionableGrid, Serializable { private static final long serialVersionUID = 5631266851555264047L; @Override public final boolean isBlocked(short x, short y) { return flagsGrid.isBlocked(x, y) || isLandscapeBlocking(x, y); } @Override public final void changedPartitionAt(short x, short y) { landmarksCorrectionThread.addLandmarkedPosition(new ShortPoint2D(x, y)); } @Override public final void setDebugColor(final short x, final short y, Color color) { debugColors[x][y] = color; } } class FogOfWarGrid implements IFogOfWarGrid { @Override public final short getHeight() { return height; } @Override public final short getWidth() { return width; } @Override public final IMovable getMovableAt(int x, int y) { return movableGrid.getMovableAt((short) x, (short) y); } @Override public final IMapObject getMapObjectsAt(int x, int y) { return objectsGrid.getObjectsAt((short) x, (short) y); } } }
package jwbroek.cuelib.tools.trackcutter; import java.io.File; import jwbroek.cuelib.Position; import jwbroek.cuelib.TrackData; /** * Represents a processing action for a TrackCutter instance. * * @author jwbroek */ public class TrackCutterProcessingAction { /** * Starting position for the track. */ private Position startPosition; /** * Ending position for the track. */ private Position endPosition; /** * The corresponding TrackData instance. */ private TrackData trackData; /** * Whether or not this action concerns the pregap of a track. (These may be * treated as separate tracks.) */ private boolean isPregap; /** * The configuration of the TrackCutter. Undefined behavior occurs when the * configuration does not match the configuration of the TrackCutter. */ private TrackCutterConfiguration configuration; /** * The target file for the cutting operation. */ private File cutFile = null; /** * The target file for the post-processing operation. */ private File postProcessFile = null; /** * The post-processing command. */ private String postProcessingCommand = null; /** * Construct a processing action for a TrackCutter. * * @param startPosition * Starting position for the track. * @param endPosition * Ending position for the track. * @param trackData * The TrackData instance corresponding to the processing action. * @param isPregap * Whether or not this action concerns the pregap of a track. (These * may be treated as separate tracks.) * @param configuration * The TrackCutterConfiguration of the TrackCutter for which this * action is intended. */ public TrackCutterProcessingAction(Position startPosition, Position endPosition, TrackData trackData, boolean isPregap, TrackCutterConfiguration configuration) { this.startPosition = startPosition; this.endPosition = endPosition; this.trackData = trackData; this.isPregap = isPregap; this.configuration = configuration; } /** * Get a File instance representing the track after cutting. * * @return A File instance representing the track after cutting. */ public File getCutFile() { if (this.cutFile == null) { this.cutFile = this.configuration.getCutFile(this); } return this.cutFile; } /** * Get a File instance representing the track after post-processing. * * @return A File instance representing the track after post-processing. */ public File getPostProcessFile() { if (this.postProcessFile == null) { this.postProcessFile = this.configuration.getPostProcessFile(this); } return this.postProcessFile; } /** * Get the command to be used for post-processing. * * @return The command to be used for post-processing. */ public String getPostProcessCommand() { if (this.postProcessingCommand == null) { this.postProcessingCommand = this.configuration .getPostProcessCommand(this); } return this.postProcessingCommand; } /** * Get a File instance where standard output of the postprocessing step should be redirected to. * @return A File instance where standard output of the postprocessing step should be redirected to. */ public File getStdOutRedirectFile() { if (this.configuration.getRedirectStdOut()) { return new File(this.getPostProcessFile().getPath() + ".out"); } else { return null; } } /** * Get a File instance where error output of the postprocessing step should be redirected to. * @return A File instance where error output of the postprocessing step should be redirected to. */ public File getErrRedirectFile() { if (this.configuration.getRedirectStdOut()) { return new File(this.getPostProcessFile().getPath() + ".err"); } else { return null; } } /** * Get the starting position for the track. * @return The starting position for the track. */ public Position getStartPosition() { return this.startPosition; } /** * Get the ending position for the track. * @return The ending position for the track. */ public Position getEndPosition() { return this.endPosition; } /** * Get the associated TrackData. * @return The associated TrackData. */ public TrackData getTrackData() { return this.trackData; } /** * Get whether or not this actions concerns a pregap track. * @return Whether or not this actions concerns a pregap track. */ public boolean getIsPregap() { return this.isPregap; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pl.umk.mat.zawodyweb.judge; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.List; import java.util.Properties; import java.util.Vector; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import pl.umk.mat.zawodyweb.checker.CheckerInterface; import pl.umk.mat.zawodyweb.checker.CheckerResult; import pl.umk.mat.zawodyweb.checker.TestInput; import pl.umk.mat.zawodyweb.checker.TestOutput; import pl.umk.mat.zawodyweb.compiler.Code; import pl.umk.mat.zawodyweb.compiler.CompilerInterface; import pl.umk.mat.zawodyweb.compiler.Program; import pl.umk.mat.zawodyweb.database.CheckerErrors; import pl.umk.mat.zawodyweb.database.DAOFactory; import pl.umk.mat.zawodyweb.database.SubmitsResultEnum; import pl.umk.mat.zawodyweb.database.hibernate.HibernateUtil; import pl.umk.mat.zawodyweb.database.pojo.Classes; import pl.umk.mat.zawodyweb.database.pojo.Results; import pl.umk.mat.zawodyweb.database.pojo.Submits; import pl.umk.mat.zawodyweb.database.pojo.Tests; /** * * @author lukash2k */ public class MainJudge { private static final org.apache.log4j.Logger logger = Logger.getLogger(MainJudge.class); private static Vector<ClassInfo> classes = new Vector<ClassInfo>(); private static Properties properties = new Properties(); private static long delayConnect; private static void connectToJudgeManager() throws IOException, InstantiationException, IllegalAccessException { Socket sock = null; /* connecting to JudgeManager */ try { sock = new Socket(InetAddress.getByName(properties.getProperty("JUDGEMANAGER_HOST")), Integer.parseInt(properties.getProperty("JUDGEMANAGER_PORT"))); DataInputStream input = new DataInputStream(sock.getInputStream()); DataOutputStream output = new DataOutputStream(sock.getOutputStream()); logger.info("Connection with JudgeManager on " + properties.getProperty("JUDGEMANAGER_HOST") + ":" + properties.getProperty("JUDGEMANAGER_PORT") + "..."); while (15 == 15) { /* receiving submit_id */ int id; try { id = input.readInt(); if (id == 0) { continue; } logger.info("Received submit id: " + id); } catch (IOException ex) { logger.error("Connection to JudgeManager closed, shutting down Judge..."); break; } logger.info("Setting submit status to PROCESS..."); /* change submit status to PROCESS */ Transaction transaction = null; try { transaction = HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); Submits submit = DAOFactory.DEFAULT.buildSubmitsDAO().getById(id); submit.setResult(SubmitsResultEnum.PROCESS.getCode()); DAOFactory.DEFAULT.buildSubmitsDAO().saveOrUpdate(submit); transaction.commit(); /* getting submit */ transaction = HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); if (!sock.isConnected()) { logger.error("Connection to JudgeManager closed, shutting down Judge..."); break; } submit = DAOFactory.DEFAULT.buildSubmitsDAO().getById(id); byte[] codeText = submit.getCode(); String filename = submit.getFilename(); if (filename != null && !filename.isEmpty()) { properties.setProperty("COMPILED_FILENAME", filename); properties.setProperty("CODE_FILENAME", filename); } Classes compilerClasses = submit.getLanguages().getClasses(); /* downloading compiler class */ logger.info("Downloading compiler class..."); int iVectorClassInfo; boolean found = false; for (iVectorClassInfo = 0; iVectorClassInfo < classes.size(); ++iVectorClassInfo) { if (classes.get(iVectorClassInfo).getId() == compilerClasses.getId()) { found = true; break; } } CompilerInterface compiler; if (found) { if (classes.get(iVectorClassInfo).getVersion() >= compilerClasses.getVersion()) { compiler = (CompilerInterface) new CompiledClassLoader().loadCompiledClass(classes.get(iVectorClassInfo).getFilename(), classes.get(iVectorClassInfo).getCode()).newInstance(); } else { classes.get(iVectorClassInfo).setVersion(compilerClasses.getVersion()); classes.get(iVectorClassInfo).setCode(compilerClasses.getCode()); compiler = (CompilerInterface) new CompiledClassLoader().loadCompiledClass(classes.get(iVectorClassInfo).getFilename(), classes.get(iVectorClassInfo).getCode()).newInstance(); } } else { classes.add(new ClassInfo(compilerClasses.getId(), compilerClasses.getFilename(), compilerClasses.getCode(), compilerClasses.getVersion())); compiler = (CompilerInterface) new CompiledClassLoader().loadCompiledClass(compilerClasses.getFilename(), compilerClasses.getCode()).newInstance(); } properties.setProperty("CODEFILE_EXTENSION", submit.getLanguages().getExtension()); compiler.setProperties(properties); /* downloading diff class */ logger.info("Downloading diff class..."); Classes diffClasses = submit.getProblems().getClasses(); found = false; for (iVectorClassInfo = 0; iVectorClassInfo < classes.size(); iVectorClassInfo++) { if (classes.get(iVectorClassInfo).getId() == diffClasses.getId()) { found = true; break; } } CheckerInterface checker; if (found) { if (classes.get(iVectorClassInfo).getVersion() >= diffClasses.getVersion()) { checker = (CheckerInterface) new CompiledClassLoader().loadCompiledClass(classes.get(iVectorClassInfo).getFilename(), classes.get(iVectorClassInfo).getCode()).newInstance(); } else { classes.get(iVectorClassInfo).setVersion(diffClasses.getVersion()); classes.get(iVectorClassInfo).setCode(diffClasses.getCode()); checker = (CheckerInterface) new CompiledClassLoader().loadCompiledClass(classes.get(iVectorClassInfo).getFilename(), classes.get(iVectorClassInfo).getCode()).newInstance(); } } else { classes.add(new ClassInfo(diffClasses.getId(), diffClasses.getFilename(), diffClasses.getCode(), diffClasses.getVersion())); checker = (CheckerInterface) new CompiledClassLoader().loadCompiledClass(diffClasses.getFilename(), diffClasses.getCode()).newInstance(); } /* compilation */ Code code = new Code(codeText, compiler); logger.info("Trying to compile the code..."); Program program = code.compile(); /* downloading tests */ logger.info("Downloading tests..."); Criteria c = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Tests.class); c.add(Restrictions.eq("problems.id", submit.getProblems().getId())); c.addOrder(Order.asc("testorder")); List<Tests> tests = c.list(); TestInput testInput; TestOutput testOutput; boolean undefinedResult = false; /* TESTING */ logger.info("Starting tests..."); for (Tests test : tests) { testInput = new TestInput(test.getInput(), test.getMaxpoints(), test.getTimelimit(), submit.getProblems().getMemlimit()); testOutput = new TestOutput(test.getOutput()); CheckerResult result = checker.check(program, testInput, testOutput); if (result.getResult() == CheckerErrors.UNDEF) { undefinedResult = true; break; } /* saving result to database */ Results dbResult = new Results(); dbResult.setMemory(result.getMemUsed()); dbResult.setRuntime(result.getRuntime()); if (result.getDescription() != null) { dbResult.setNotes(result.getDescription().replaceAll("[\000-\007]", " ")); } dbResult.setPoints(result.getPoints()); dbResult.setSubmitResult(result.getResult()); dbResult.setSubmits(submit); dbResult.setTests(test); DAOFactory.DEFAULT.buildResultsDAO().save(dbResult); logger.info("Test finished."); } /* finish testing */ logger.info("All tests finished. Closing program."); program.closeProgram(); /* successfully completed? */ if (undefinedResult == false) { logger.info("Saving results to database."); submit.setResult(SubmitsResultEnum.DONE.getCode()); DAOFactory.DEFAULT.buildSubmitsDAO().saveOrUpdate(submit); transaction.commit(); } else { logger.error("Some of the tests got UNDEFINED result -- this should not happend."); transaction.rollback(); } } catch (Exception e) { logger.error("Exception occurs -- rolling back.", e); if (transaction != null) { transaction.rollback(); } } /* send ACK to JudgeManager */ logger.info("Processing SubmitID: " + id + " finished."); output.writeInt(id); } // dalton said: "never": HibernateUtil.getSessionFactory().getCurrentSession().close(); } finally { /* closing socket (when 15!=15) */ sock.close(); } } /** * @param args the command line arguments */ public static void main(String[] args) { String configFile = MainJudge.class.getResource(".").getPath() + "configuration.xml"; if (args.length == 1 && !args[0].isEmpty()) { configFile = args[0]; } /* Default settings for properties */ properties.setProperty("JUDGEMANAGER_HOST", "127.0.0.1"); properties.setProperty("JUDGEMANAGER_PORT", "8088"); properties.setProperty("JUDGEMANAGER_DELAY_CONNECT", "10000"); properties.setProperty("COMPILED_DIR", ""); properties.setProperty("CODE_DIR", ""); properties.setProperty("COMPILED_FILENAME", "a"); properties.setProperty("CODE_FILENAME", "a"); properties.setProperty("COMPILE_TIMEOUT", "60000"); properties.setProperty("JAVA_POLICY", ""); try { logger.info("Reading configuration file from " + configFile + "..."); properties.loadFromXML(new FileInputStream(configFile)); } catch (Exception ex) { logger.error(ex.getMessage()); } try { delayConnect = Integer.parseInt(properties.getProperty("JUDGEMANAGER_DELAY_CONNECT")); } catch (NumberFormatException ex) { delayConnect = 10 * 1000; } logger.info("JUDGEMANAGER_HOST = " + properties.getProperty("JUDGEMANAGER_HOST")); logger.info("JUDGEMANAGER_PORT = " + properties.getProperty("JUDGEMANAGER_PORT")); logger.info("JUDGEMANAGER_DELAY_CONNECT = " + properties.getProperty("JUDGEMANAGER_DELAY_CONNECT")); logger.info("COMPILED_DIR = " + properties.getProperty("COMPILED_DIR")); logger.info("CODE_DIR = " + properties.getProperty("CODE_DIR")); logger.info("COMPILED_FILENAME = " + properties.getProperty("COMPILED_FILENAME")); logger.info("CODE_FILENAME = " + properties.getProperty("CODE_FILENAME")); logger.info("COMPILE_TIMEOUT = " + properties.getProperty("COMPILE_TIMEOUT")); logger.info("JAVA_POLICY = " + properties.getProperty("JAVA_POLICY")); while (true) { try { connectToJudgeManager(); } catch (Exception ex) { logger.error("Exception occurs: ", ex); try { Thread.sleep(delayConnect); } catch (InterruptedException ex1) { } } } } }
package ValkyrienWarfareControl; import java.io.File; import ValkyrienWarfareBase.ValkyrienWarfareMod; import ValkyrienWarfareControl.Block.BlockAntiGravEngine; import ValkyrienWarfareControl.Block.BlockBalloonBurner; import ValkyrienWarfareControl.Block.BlockDopedEtherium; import ValkyrienWarfareControl.Block.BlockHovercraftController; import ValkyrienWarfareControl.Block.BlockNormalEngine; import ValkyrienWarfareControl.Block.BlockRedstoneEngine; import ValkyrienWarfareControl.FullBalloonControl.ManualShipControllerBlock; import ValkyrienWarfareControl.FullBalloonControl.ManualShipControllerTileEntity; import ValkyrienWarfareControl.GUI.ControlGUIHandler; import ValkyrienWarfareControl.Item.ItemSystemLinker; import ValkyrienWarfareControl.Network.EntityFixMessage; import ValkyrienWarfareControl.Network.EntityFixMessageHandler; import ValkyrienWarfareControl.Network.HovercraftControllerGUIInputHandler; import ValkyrienWarfareControl.Network.HovercraftControllerGUIInputMessage; import ValkyrienWarfareControl.Piloting.PilotControlsMessage; import ValkyrienWarfareControl.Piloting.PilotControlsMessageHandler; import ValkyrienWarfareControl.Piloting.SetShipPilotMessage; import ValkyrienWarfareControl.Piloting.SetShipPilotMessageHandler; import ValkyrienWarfareControl.TileEntity.AntiGravEngineTileEntity; import ValkyrienWarfareControl.TileEntity.BalloonBurnerTileEntity; import ValkyrienWarfareControl.TileEntity.TileEntityHoverController; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLStateEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; @Mod(modid = ValkyrienWarfareControlMod.MODID, name = ValkyrienWarfareControlMod.MODNAME, version = ValkyrienWarfareControlMod.MODVER) public class ValkyrienWarfareControlMod { public static Configuration config; public static final String MODID = "valkyrienwarfarecontrol"; public static final String MODNAME = "Valkyrien Warfare Control"; public static final String MODVER = "0.3b"; public static ValkyrienWarfareControlMod instance; public static SimpleNetworkWrapper controlNetwork; public Block basicEngine; public Block advancedEngine; public Block eliteEngine; public Block ultimateEngine; // Couldn't think of what to name these, so I went with the Mekanism naming style public Block redstoneEngine; public Block basicHoverController; public Block antigravityEngine; public Block dopedEtherium; public Block balloonBurner; public Block manualController; public Item systemLinker; @SidedProxy(clientSide = "ValkyrienWarfareControl.ClientProxyControl", serverSide = "ValkyrienWarfareControl.CommonProxyControl") public static CommonProxyControl proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { instance = this; config = new Configuration(new File(ValkyrienWarfareMod.getWorkingFolder() + "/config/valkyrienwarfarecontrol.cfg")); config.load(); registerBlocks(event); registerTileEntities(event); registerItems(event); registerRecipies(event); registerNetworks(event); proxy.preInit(event); config.save(); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); NetworkRegistry.INSTANCE.registerGuiHandler(this, new ControlGUIHandler()); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); } private void registerBlocks(FMLStateEvent event) { double basicEnginePower = config.get(Configuration.CATEGORY_GENERAL, "basicEnginePower", 4000D, "Engine power for the basic Engine").getDouble(); double advancedEnginePower = config.get(Configuration.CATEGORY_GENERAL, "advancedEnginePower", 6000D, "Engine power for the advanced Engine").getDouble(); double eliteEnginePower = config.get(Configuration.CATEGORY_GENERAL, "eliteEnginePower", 8000D, "Engine power for the elite Engine").getDouble(); double ultimateEnginePower = config.get(Configuration.CATEGORY_GENERAL, "ultimateEnginePower", 16000D, "Engine power for the ultimate Engine").getDouble(); double redstoneEnginePower = config.get(Configuration.CATEGORY_GENERAL, "redstoneEnginePower", 500D, "Multiplied by the redstone power (0-15) to the Redstone Engine").getDouble(); basicEngine = new BlockNormalEngine(Material.WOOD, basicEnginePower).setHardness(5f).setUnlocalizedName("basicEngine").setRegistryName(ValkyrienWarfareMod.MODID, "basicEngine").setCreativeTab(CreativeTabs.TRANSPORTATION); advancedEngine = new BlockNormalEngine(Material.WOOD, advancedEnginePower).setHardness(6f).setUnlocalizedName("advancedEngine").setRegistryName(ValkyrienWarfareMod.MODID, "advancedEngine").setCreativeTab(CreativeTabs.TRANSPORTATION); eliteEngine = new BlockNormalEngine(Material.WOOD, eliteEnginePower).setHardness(8f).setUnlocalizedName("eliteEngine").setRegistryName(ValkyrienWarfareMod.MODID, "eliteEngine").setCreativeTab(CreativeTabs.TRANSPORTATION); ultimateEngine = new BlockNormalEngine(Material.WOOD, ultimateEnginePower).setHardness(10f).setUnlocalizedName("ultimateEngine").setRegistryName(ValkyrienWarfareMod.MODID, "ultimateEngine").setCreativeTab(CreativeTabs.TRANSPORTATION); redstoneEngine = new BlockRedstoneEngine(Material.REDSTONE_LIGHT, redstoneEnginePower).setHardness(7.0f).setUnlocalizedName("redstoneEngine").setRegistryName(ValkyrienWarfareMod.MODID, "redstoneEngine").setCreativeTab(CreativeTabs.TRANSPORTATION); basicHoverController = new BlockHovercraftController(Material.IRON).setHardness(10f).setUnlocalizedName("basichovercraftcontroller").setRegistryName(ValkyrienWarfareMod.MODID, "basichovercraftcontroller").setCreativeTab(CreativeTabs.TRANSPORTATION); antigravityEngine = new BlockAntiGravEngine(Material.IRON).setHardness(8f).setUnlocalizedName("antigravengine").setUnlocalizedName("antigravengine").setRegistryName(ValkyrienWarfareMod.MODID, "antigravengine").setCreativeTab(CreativeTabs.TRANSPORTATION); dopedEtherium = new BlockDopedEtherium(Material.GLASS).setHardness(4f).setUnlocalizedName("dopedetherium").setRegistryName(MODID, "dopedetherium").setCreativeTab(CreativeTabs.TRANSPORTATION); balloonBurner = new BlockBalloonBurner(Material.IRON).setHardness(4f).setUnlocalizedName("ballonburner").setRegistryName(MODID, "ballonburner").setCreativeTab(CreativeTabs.TRANSPORTATION); manualController = new ManualShipControllerBlock(Material.IRON).setHardness(4f).setUnlocalizedName("manualshipcontroller").setRegistryName(MODID, "manualshipcontroller").setCreativeTab(CreativeTabs.TRANSPORTATION); GameRegistry.registerBlock(basicEngine); GameRegistry.registerBlock(advancedEngine); GameRegistry.registerBlock(eliteEngine); GameRegistry.registerBlock(ultimateEngine); GameRegistry.registerBlock(redstoneEngine); GameRegistry.registerBlock(basicHoverController); GameRegistry.registerBlock(antigravityEngine); GameRegistry.registerBlock(dopedEtherium); GameRegistry.registerBlock(balloonBurner); GameRegistry.registerBlock(manualController); } private void registerTileEntities(FMLStateEvent event) { TileEntity.addMapping(TileEntityHoverController.class, "tilehovercontroller"); TileEntity.addMapping(AntiGravEngineTileEntity.class, "tileantigravengine"); TileEntity.addMapping(BalloonBurnerTileEntity.class, "tileballoonburner"); TileEntity.addMapping(ManualShipControllerTileEntity.class, "tilemanualshipcontroller"); } private void registerItems(FMLStateEvent event) { systemLinker = new ItemSystemLinker().setUnlocalizedName("systemlinker").setRegistryName(MODID, "systemlinker").setCreativeTab(CreativeTabs.TRANSPORTATION).setMaxStackSize(1); GameRegistry.registerItem(systemLinker); } private void registerRecipies(FMLStateEvent event) { GameRegistry.addRecipe(new ItemStack(basicEngine), new Object[] { "IWW", "IPP", "IWW", 'W', Item.getItemFromBlock(Blocks.PLANKS), 'P', Item.getItemFromBlock(Blocks.PISTON), 'I', Items.IRON_INGOT }); GameRegistry.addRecipe(new ItemStack(basicHoverController), new Object[] { "III", "TCT", "III", 'I', Item.getItemFromBlock(Blocks.IRON_BLOCK), 'C', Items.COMPASS, 'T', Item.getItemFromBlock(Blocks.CRAFTING_TABLE) }); GameRegistry.addRecipe(new ItemStack(antigravityEngine, 3), new Object[] { "IWI", "GDG", "IWI", 'W', Item.getItemFromBlock(Blocks.PLANKS), 'G', Item.getItemFromBlock(Blocks.GOLD_BLOCK), 'I', Item.getItemFromBlock(Blocks.IRON_BLOCK), 'D', Item.getItemFromBlock(Blocks.DIAMOND_BLOCK) }); GameRegistry.addRecipe(new ItemStack(systemLinker), new Object[] { "IR ", " DR", "I I", 'I', Items.IRON_INGOT, 'D', Items.DIAMOND, 'R', Items.REDSTONE }); } private void registerNetworks(FMLStateEvent event) { controlNetwork = NetworkRegistry.INSTANCE.newSimpleChannel("controlNetwork"); controlNetwork.registerMessage(HovercraftControllerGUIInputHandler.class, HovercraftControllerGUIInputMessage.class, 0, Side.SERVER); controlNetwork.registerMessage(PilotControlsMessageHandler.class, PilotControlsMessage.class, 1, Side.SERVER); controlNetwork.registerMessage(EntityFixMessageHandler.class, EntityFixMessage.class, 2, Side.CLIENT); controlNetwork.registerMessage(SetShipPilotMessageHandler.class, SetShipPilotMessage.class, 3, Side.CLIENT); } }
package au.com.agic.apptesting.utils.impl; import au.com.agic.apptesting.constants.Constants; import au.com.agic.apptesting.utils.CleanupUtils; import org.apache.commons.io.FileUtils; import java.io.File; import java.util.Arrays; import java.util.regex.Pattern; /** * An implementation of the cleanup service */ public class CleanupUtilsImpl implements CleanupUtils { private static final Pattern REPORT_RE = Pattern.compile( "(" + Constants.THREAD_NAME_PREFIX + "\\d+\\.(html|xml|txt|json)|" + Pattern.quote(Constants.MERGED_REPORT) + ")"); @Override public void cleanupOldReports() { Arrays.stream(new File(".").listFiles()) .filter(file -> REPORT_RE.matcher(file.getName()).matches()) .forEach(FileUtils::deleteQuietly); } }
package br.senac.tads.pi3.rafamaia.exercicio01; import java.util.Scanner; /** * * @author rafael.malexandre */ public class Exercicio01 { static Scanner leitor = new Scanner(System.in); static Pessoa pessoa = new Pessoa(); static void entradaDeDados(String nome, String telefone, String data, String email) { System.out.println("*** Cadastro de Contatos ***"); System.out.println("Digite o nome:"); pessoa.setNome(leitor.nextLine()); System.out.println("Digite o e-mail:"); pessoa.setEmail(leitor.nextLine()); System.out.println("Digite o telefone:"); pessoa.setTelefone(leitor.nextLine()); System.out.println("Digite o data de nascimento:"); pessoa.setData(leitor.nextLine()); System.out.println("*** Contato salvo ***"); } public static void main(String[] args) { String nome = null, telefone = null, data = null, email = null; entradaDeDados(nome, telefone, data, email); } public static void saidaDeDados(Pessoa pessoa) { System.out.println("***Dados do contato***"); System.out.println("Nome:" + pessoa.getNome()); System.out.println("Email:" + pessoa.getEmail()); System.out.println("Telefone:" + pessoa.getTelefone()); System.out.println("Data Nascimento:" + pessoa.getData()); } }
package cc.twittertools.scripts; import static cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler.DATA_OPTION; import static cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler.NOFOLLOW_OPTION; import static cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler.OUTPUT_OPTION; import static cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler.REPAIR_OPTION; import java.io.File; import java.io.FileOutputStream; import java.nio.channels.FileLock; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.io.Files; import cc.twittertools.corpus.demo.ReadStatuses; import cc.twittertools.download.AsyncEmbeddedJsonStatusBlockCrawler; /** * Given a list of ID files, and a number of tasks, starts downloading * simultaneously from the files. * @author bfeeney * */ public class BulkEmbeddedJsonDownloader { private final static Logger LOG = Logger.getLogger(BulkEmbeddedJsonDownloader.class); private final static File LOCK_FILE = new File ("/home/bfeeney/trec.lock.file"); private final static File STARTED_TASKS_FILE = new File ("/home/bfeeney/trec.running.tasks"); private final static File COMPLETED_TASKS_FILE = new File ("/home/bfeeney/trec.completed.tasks"); /** * Locks the lock-file, then reads in the task status file. If the given * input file already exists in the task-status file, returns false. If * the given file doesn't exist, it's added to the task status file, and * we return true. * @param inpath path of the input file, which should serve as a * unique ID for the job * @return true if the job should be undertaken, false if the job should * be abandoned (on the premise that it's already done/in-progress) */ private final static boolean shouldStart (String inpath) throws Exception { synchronized (BulkEmbeddedJsonDownloader.class) { inpath = inpath.toUpperCase(); FileOutputStream out = new FileOutputStream(LOCK_FILE, /* append = */ true); try { FileLock lock = null; try { lock = out.getChannel().lock(); List<String> lines = Files.readLines(STARTED_TASKS_FILE, Charsets.UTF_8); if (! lines.contains(inpath)) { lines.add(inpath); Files.write (Joiner.on('\n').join(lines), STARTED_TASKS_FILE, Charsets.UTF_8); return true; } } catch (Exception e) { LOG.error("Can't acquire lock on lock-file " + LOCK_FILE + " or can't access running tasks file " + STARTED_TASKS_FILE + " : " + e.getMessage(), e); throw e; } finally { if (lock != null) lock.release(); } } finally { out.close(); } return false; } } /** * Locks the lock-file, then records that this task has been completed * @param inpath path of the input file, which should serve as a * unique ID for the job * @return true if the job should be undertaken, false if the job should * be abandoned (on the premise that it's already done/in-progress) */ private final static void markCompleted (String inpath, int crawlSize) throws Exception { synchronized (BulkEmbeddedJsonDownloader.class) { inpath = inpath.toUpperCase(); FileOutputStream out = new FileOutputStream(LOCK_FILE); try { FileLock lock = null; try { lock = out.getChannel().lock(); List<String> lines = Files.readLines(COMPLETED_TASKS_FILE, Charsets.UTF_8); lines.add(inpath + '\t' + crawlSize); Files.write (Joiner.on('\n').join(lines), COMPLETED_TASKS_FILE, Charsets.UTF_8); } catch (Exception e) { LOG.error("Can't acquire lock on lock-file " + LOCK_FILE + " or can't access completed tasks file " + COMPLETED_TASKS_FILE + " : " + e.getMessage(), e); throw e; } finally { if (lock != null) lock.release(); } } finally { out.close(); } } } private final static class DownloadTask implements Callable<Integer> { public final String inpath; public final String outpath; public DownloadTask(String inpath, String outpath) { super(); this.inpath = inpath; this.outpath = outpath; } @Override public Integer call() throws Exception { if (! shouldStart (inpath)) { LOG.info ("Skipping job as it's already been started - " + inpath); return 0; } int completedCount = 0; try { completedCount = new AsyncEmbeddedJsonStatusBlockCrawler( new File(inpath), outpath, /* repair = */ null, /* noFollow = */ false ).fetch(); } catch (Exception e) { LOG.error ("Failed to download files for task " + inpath + " : " + e.getMessage(), e); return 0; } LOG.info("Downloaded " + completedCount + " files from " + inpath); markCompleted (inpath, completedCount); return completedCount; } } public static final String TASK_COUNT_OPTION = "taskcount"; @SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Files.touch (LOCK_FILE); Files.touch (STARTED_TASKS_FILE); Files.touch (COMPLETED_TASKS_FILE); Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("data file with tweet ids").create(DATA_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("output file (*.gz)").create(OUTPUT_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("output repair file (can be used later as a data file)").create(REPAIR_OPTION)); options.addOption(OptionBuilder.withArgName("taskcount").hasArg() .withDescription("number of simultaneous downloads to attempt").create(TASK_COUNT_OPTION)); options.addOption(NOFOLLOW_OPTION, NOFOLLOW_OPTION, false, "don't follow 301 redirects"); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(DATA_OPTION) || !cmdline.hasOption(OUTPUT_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ReadStatuses.class.getName(), options); System.exit(-1); } String data = cmdline.getOptionValue(DATA_OPTION); String output = cmdline.getOptionValue(OUTPUT_OPTION); String repair = cmdline.getOptionValue(REPAIR_OPTION); boolean noFollow = cmdline.hasOption(NOFOLLOW_OPTION); int taskCount = Integer.parseInt ( StringUtils.defaultIfBlank( cmdline.getOptionValue(TASK_COUNT_OPTION), "1" ) ); ExecutorService executor = Executors.newFixedThreadPool(taskCount); String[] inFiles = new File (data).list(); Arrays.sort (inFiles); for (String inFile : inFiles) { String outFile = output + File.separator + new File (inFile).getName().replaceAll ("\\.dat", ".json.gz"); inFile = data + File.separator + inFile; executor.submit(new DownloadTask(inFile, outFile)); } executor.shutdown(); executor.awaitTermination(30, TimeUnit.DAYS); } }
package ch.sportchef.business.event.boundary; import ch.sportchef.business.event.control.EventImageService; import ch.sportchef.business.event.control.EventService; import ch.sportchef.business.event.entity.Event; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.Optional; public class EventResource { private final Long eventId; private final EventService eventService; private final EventImageService eventImageService; public EventResource(@NotNull final Long eventId, @NotNull final EventService eventService, @NotNull final EventImageService eventImageService) { this.eventId = eventId; this.eventService = eventService; this.eventImageService = eventImageService; } @GET public Event find() { final Optional<Event> event = eventService.findByEventId(eventId); if (event.isPresent()) { return event.get(); } throw new NotFoundException(String.format("event with id '%d' not found", eventId)); } @PUT public Response update(@Valid final Event event, @Context final UriInfo info) { find(); // only update existing events final Event eventToUpdate = event.toBuilder() .eventId(eventId) .build(); final Event updatedEvent = eventService.update(eventToUpdate); final URI uri = info.getAbsolutePathBuilder().build(); return Response.ok(updatedEvent).header("Location", uri.toString()).build(); } @DELETE public Response delete() { find(); // only delete existing events try { eventImageService.deleteImage(eventId); } catch (final NotFoundException e) { // ignore, event has no image } eventService.delete(eventId); return Response.noContent().build(); } @Path("image") public EventImageResource image() { find(); // only existing events can have images return new EventImageResource(eventId, eventService, eventImageService); } }
package com.akiban.qp.physicaloperator; import com.akiban.ais.model.HKeySegment; import com.akiban.qp.row.FlattenedRow; import com.akiban.qp.row.HKey; import com.akiban.qp.row.Row; import com.akiban.qp.row.RowHolder; import com.akiban.qp.rowtype.FlattenedRowType; import com.akiban.qp.rowtype.RowType; import com.akiban.server.rowdata.RowDef; import com.akiban.util.ArgumentValidation; import java.util.*; import static com.akiban.qp.physicaloperator.API.FlattenOption.*; class Flatten_HKeyOrdered extends PhysicalOperator { // Object interface @Override public String toString() { StringBuilder buffer = new StringBuilder(getClass().getSimpleName()); buffer.append("("); buffer.append(parentType); if (keepParent) { buffer.append(" KEEP"); } if (leftJoin && rightJoin) { buffer.append(" FULL "); } else if (leftJoin) { buffer.append(" LEFT "); } else if (rightJoin) { buffer.append(" RIGHT "); } else { buffer.append(" INNER "); } buffer.append(childType); if (keepChild) { buffer.append(" KEEP"); } buffer.append(")"); return buffer.toString(); } // PhysicalOperator interface @Override protected Cursor cursor(StoreAdapter adapter) { return new Execution(adapter, inputOperator.cursor(adapter)); } @Override public FlattenedRowType rowType() { return flattenType; } @Override public void findDerivedTypes(Set<RowType> derivedTypes) { inputOperator.findDerivedTypes(derivedTypes); derivedTypes.add(flattenType); } @Override public List<PhysicalOperator> getInputOperators() { List<PhysicalOperator> result = new ArrayList<PhysicalOperator>(1); result.add(inputOperator); return result; } @Override public String describePlan() { return describePlan(inputOperator); } // Flatten_HKeyOrdered interface public Flatten_HKeyOrdered(PhysicalOperator inputOperator, RowType parentType, RowType childType, API.JoinType joinType, EnumSet<API.FlattenOption> options) { ArgumentValidation.notNull("parentType", parentType); ArgumentValidation.notNull("childType", childType); ArgumentValidation.notNull("flattenType", joinType); assert parentType != null; assert childType != null; this.inputOperator = inputOperator; this.parentType = parentType; this.childType = childType; this.flattenType = parentType.schema().newFlattenType(parentType, childType); boolean fullJoin = joinType.equals(API.JoinType.FULL_JOIN); this.leftJoin = fullJoin || joinType.equals(API.JoinType.LEFT_JOIN); this.rightJoin = fullJoin || joinType.equals(API.JoinType.RIGHT_JOIN); this.keepParent = options.contains(KEEP_PARENT); this.keepChild = options.contains(KEEP_CHILD); this.leftJoinShortensHKey = options.contains(LEFT_JOIN_SHORTENS_HKEY); if (this.leftJoinShortensHKey) { ArgumentValidation.isTrue("flags contains LEFT_JOIN_SHORTENS_HKEY but not LEFT_JOIN", leftJoin); } List<HKeySegment> childHKeySegments = childType.hKey().segments(); HKeySegment lastChildHKeySegment = childHKeySegments.get(childHKeySegments.size() - 1); RowDef childRowDef = (RowDef) lastChildHKeySegment.table().rowDef(); this.childOrdinal = childRowDef.getOrdinal(); this.nChildHKeySegmentFields = lastChildHKeySegment.columns().size(); this.parentHKeySegments = parentType.hKey().segments().size(); } // Class state private static final int MAX_PENDING = 2; // Object state private final PhysicalOperator inputOperator; private final RowType parentType; private final RowType childType; private final FlattenedRowType flattenType; private final boolean leftJoin; private final boolean rightJoin; private final boolean keepParent; private final boolean keepChild; private final boolean leftJoinShortensHKey; // For constructing a left-join hkey private final int childOrdinal; private final int nChildHKeySegmentFields; private final int parentHKeySegments; // Inner classes private class Execution implements Cursor { // Cursor interface @Override public void open(Bindings bindings) { input.open(bindings); } @Override public Row next() { Row outputRow = pending.take(); Row inputRow; while (outputRow == null && (((inputRow = input.next()) != null) || parent.isNotNull())) { if (readyForLeftJoinRow(inputRow)) { // child rows are processed immediately. parent rows are not, // because when seen, we don't know if the next row will be another // parent, a child, a row of child type that is not actually a child, // a row of type other than parent or child, or end of stream. If inputRow is // null, then input is exhausted, and the only possibly remaining row would // be due to a childless parent waiting to be processed. generateLeftJoinRow(parent.get()); } if (inputRow == null) { // With inputRow == null, we needed parent to create a left join row if required. That's // been done. set parent to null so that the loop exits. setParent(null); } else { RowType inputRowType = inputRow.rowType(); if (inputRowType == parentType) { if (keepParent) { addToPending(inputRow); } setParent(inputRow); } else if (inputRowType == childType) { if (keepChild) { addToPending(inputRow); } if (parent.isNotNull() && parent.get().ancestorOf(inputRow)) { // child is not an orphan generateInnerJoinRow(parent.get(), inputRow); childlessParent = false; } else { // child is an orphan setParent(null); generateRightJoinRow(inputRow); } } else { addToPending(inputRow); } } outputRow = pending.take(); } return outputRow; } @Override public void close() { parent.set(null); pending.clear(); input.close(); } // Execution interface Execution(StoreAdapter adapter, Cursor input) { this.adapter = adapter; this.input = input; this.leftJoinHKey = adapter.newHKey(childType); } // For use by this class private void generateInnerJoinRow(Row parent, Row child) { assert parent != null; assert child != null; pending.add(new FlattenedRow(flattenType, parent, child, child.hKey())); } private void generateLeftJoinRow(Row parent) { assert parent != null; if (leftJoin) { HKey hKey; if (leftJoinShortensHKey) { hKey = parent.hKey(); } else { if (parent.hKey().segments() < parentHKeySegments) { throw new IncompatibleRowException( String.format("%s: parent hkey %s has been shortened by an earlier Flatten, " + "so this Flatten should specify LEFT_JOIN_SHORTENS_HKEY also", this, parent.hKey())); } // Copy leftJoinHKey to avoid aliasing problems. (leftJoinHKey changes on each parent row.) hKey = adapter.newHKey(childType); leftJoinHKey.copyTo(hKey); } pending.add(new FlattenedRow(flattenType, parent, null, hKey)); // Prevent generation of another left join row for the same parent childlessParent = false; } } private void generateRightJoinRow(Row child) { assert child != null; if (rightJoin) { pending.add(new FlattenedRow(flattenType, null, child, child.hKey())); } } private void addToPending(Row row) { pending.add(row); } private void setParent(Row newParent) { parent.set(newParent); if (leftJoin && newParent != null) { computeLeftJoinHKey(newParent); childlessParent = true; } } private void computeLeftJoinHKey(Row newParent) { HKey parentHKey = newParent.hKey(); parentHKey.copyTo(leftJoinHKey); leftJoinHKey.extendWithOrdinal(childOrdinal); for (int i = 0; i < nChildHKeySegmentFields; i++) { leftJoinHKey.extendWithNull(); } } private boolean readyForLeftJoinRow(Row inputRow) { boolean readyForLeftJoinRow = false; if (leftJoin && childlessParent && parent.isNotNull()) { if (inputRow == null) { readyForLeftJoinRow = true; } else if (!parent.get().ancestorOf(inputRow)) { readyForLeftJoinRow = true; } else if (inputRow.rowType() == childType) { // inputRow is a child of parent (since ancestorOf is true) readyForLeftJoinRow = false; } else { // Equality can occur when an input stream contains both flattened rows and the input // to the flattening, e.g. an Order row, o, and a flatten(Customer, Order) // row derived from o. Ordering is not well-defined in this case, so neither < nor <= is // clearly preferable. readyForLeftJoinRow = leftJoinHKey.compareTo(inputRow.hKey()) < 0; } } return readyForLeftJoinRow; } // Object state private final StoreAdapter adapter; private final Cursor input; private final RowHolder<Row> parent = new RowHolder<Row>(); private final PendingRows pending = new PendingRows(MAX_PENDING); private final HKey leftJoinHKey; private boolean childlessParent; } }
package com.codingrodent.InMemoryRecordStore.record; import com.codingrodent.InMemoryRecordStore.core.IMemoryStore; import com.codingrodent.InMemoryRecordStore.util.BitTwiddling; import com.codingrodent.InMemoryRecordStore.utility.Utilities; public class Writer { private final static byte ZERO = (byte) 0; private final static byte ONE = (byte) 1; private final RecordDescriptor recordDescriptor; private final IMemoryStore memoryStore; private final IMemoryStore.AlignmentMode mode; /** * Create a new record writer * * @param memoryStore Data storage structure * @param recordDescriptor Field type information * @param mode Alignment mode */ public Writer(final IMemoryStore memoryStore, final RecordDescriptor recordDescriptor, final IMemoryStore.AlignmentMode mode) { this.recordDescriptor = recordDescriptor; this.memoryStore = memoryStore; this.mode = mode; } /** * Write a record at the specified location * * @param loc Location * @param record Record */ public void putRecord(final int loc, final Object record) { if (!record.getClass().equals(recordDescriptor.getClazz())) { throw new IllegalArgumentException("Object supplied to writer is of the wrong type"); } Class<?> clazz = record.getClass(); int pos = 0; byte[] data = new byte[recordDescriptor.getSizeInBytes()]; for (String fieldName : recordDescriptor.getFieldNames()) { try { System.out.println(clazz.getDeclaredField(fieldName).get(record)); RecordDescriptor.FieldDetails fieldDetails = recordDescriptor.getFieldDetails(fieldName); pos = PackFieldIntoBytes(pos, data, clazz.getDeclaredField(fieldName).get(record), fieldDetails.getByteLength(), fieldDetails.getType()); } catch (Exception e) { e.printStackTrace(); } } for (byte b : data) { System.out.print(Utilities.getByte(b) + " "); } System.out.println(); int byteSize = recordDescriptor.getSizeInBytes(); int writeLocation = loc * byteSize; if ((memoryStore.getBytes() - writeLocation) < byteSize) { throw new IndexOutOfBoundsException("Write location beyond end of storage"); } memoryStore.setByteArray(writeLocation, data); } /** * Pack an annotated field into the byte storage for a record * * @param pos Write position * @param buffer Byte buffer * @param value Object to be written. Actual type from record. * @param byteLength Write length in bytes * @param type Object type * @return Next free byte in the buffer */ private int PackFieldIntoBytes(int pos, byte[] buffer, Object value, int byteLength, IMemoryStore.Type type) { // Don't forget - you can't make things longer ! switch (type) { case Bit: buffer[pos++] = (Boolean) value ? ONE : ZERO; break; case Word64: { long v = (Long) value; if (byteLength < 8) v = BitTwiddling.shrink(v, 8 * byteLength); for (int i = byteLength - 1; i >= 0; i buffer[pos + i] = (byte) (v & 0xFF); v = v >>> 8; } pos = pos + byteLength; } break; case Byte8: buffer[pos++] = (Byte) value; break; case Short16: { short v = (Short) value; if (1 == byteLength) v = BitTwiddling.shrink(v, 8); buffer[pos + 1] = (byte) (v & 0xFF); buffer[pos++] = (byte) (v >>> 8); pos++; break; } case Word32: { int v = (Integer) value; if (byteLength < 4) v = BitTwiddling.shrink(v, 8 * byteLength); for (int i = byteLength - 1; i >= 0; i buffer[pos + i] = (byte) (v & 0xFF); v = v >>> 8; } pos = pos + byteLength; break; } case Char16: { char v = (Character) value; buffer[pos + 1] = (byte) (v & 0xFF); buffer[pos++] = (byte) (v >>> 8); pos++; break; } case Void: pos = pos + byteLength; break; } return pos; } }
package com.enderio.core.common.util; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.io.FileUtils; import com.enderio.core.EnderCore; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.FileResourcePack; import net.minecraft.client.resources.IResourcePack; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.ReflectionHelper; /** * A class that can be used to inject resources from files/folders outside your * mod resources. Useful for loading textures and other assets from the config * dir or elsewhere. * <p> * To use, first construct an instance of this class, then add all your assets * using {@link #addIcon(File)}, {@link #addLang(File)}, and * {@link #addCustomFile(String, File)}. * <p> * Once all files have been added, {@link #assemble()} Will create a zip of all * the files in the {@link File directory} passed into the constructor. * <p> * Finally, {@link #inject()} will insert this resource pack into the game. * <p> * Also, {@link #setHasPackPng(Class)} allows your resource pack to have a logo. */ public class ResourcePackAssembler { private class CustomFile { private String ext; private File file; private CustomFile(String ext, File file) { this.ext = ext; this.file = file; } } public enum ModelType { BLOCK("models/block"), ITEM("models/item"), BLOCKSTATE("blockstates"); private final String path; private ModelType(String path) { this.path = path; } String getPath() { return path; } } private List<CustomFile> files = new ArrayList<CustomFile>(); private static List<IResourcePack> defaultResourcePacks; private static final String MC_META_BASE = "{\"pack\":{\"pack_format\":1,\"description\":\"%s\"}}"; private File dir; private File zip; private String name; private String mcmeta; private String modid; private String assetsPath; private boolean hasPackPng = false; private Class<?> jarClass; public ResourcePackAssembler(File directory, String packName, String modid) { this.dir = directory; this.zip = new File(dir.getAbsolutePath() + ".zip"); this.name = packName; this.modid = modid.toLowerCase(Locale.US); this.mcmeta = String.format(MC_META_BASE, this.name); this.assetsPath = "/assets/" + modid + "/"; } /** * Enables the use of a pack.png. * <p> * Will cause your mod's jar to be searched for a resource pack logo at * assets/[modid]/pack.png. * * @param jarClass * A class in your jar file. * @return The {@link ResourcePackAssembler} instance. */ public ResourcePackAssembler setHasPackPng(Class<?> jarClass) { this.jarClass = jarClass; hasPackPng = true; return this; } /** * Adds an icon file. This file will be inserted into both the block and item * texture folders. * * @param icon * The icon file. */ public void addIcon(File icon) { files.add(new CustomFile(assetsPath + "textures/items/", icon)); files.add(new CustomFile(assetsPath + "textures/blocks/", icon)); } /** * Adds a language file. This file will be inserted into the lang dir only. * * @param lang * A language file (e.g. en_US.lang) */ public void addLang(File lang) { files.add(new CustomFile(assetsPath + "lang/", lang)); } /** * Adds a model json file. This file will be inserted into the models dir only. * * @param lang * A language file (e.g. myblock.json) */ public void addModel(File model, ModelType type) { String path = assetsPath + type.getPath() + "/"; files.add(new CustomFile(path, model)); } /** * Adds a custom file to the pack. This can be added into any folder in the * pack you desire. Useful for one-off files such as sounds.json. * * @param path * The path inside the resource pack to this file. * @param file * The file to add. */ public void addCustomFile(String path, File file) { files.add(new CustomFile(path, file)); } /** * Adds the custom file at the base directory. * * @see #addCustomFile(String, File) * * @param file * The file to add. */ public void addCustomFile(File file) { addCustomFile(null, file); } /** * Assembles the resource pack. This creates a zip file with the name of the * {@link File directory} that was passed into the constructor on the same * level as that folder. * * @return The {@link ResourcePackAssembler} instance. */ public ResourcePackAssembler assemble() { EnderFileUtils.safeDeleteDirectory(dir); dir.mkdirs(); String pathToDir = dir.getAbsolutePath(); File metaFile = new File(pathToDir + "/pack.mcmeta"); try { writeNewFile(metaFile, mcmeta); if (hasPackPng) { EnderFileUtils.copyFromJar(jarClass, modid + "/" + "pack.png", new File(dir.getAbsolutePath() + "/pack.png")); } for (CustomFile custom : files) { File directory = new File(pathToDir + (custom.ext != null ? "/" + custom.ext : "")); directory.mkdirs(); FileUtils.copyFile(custom.file, new File(directory.getAbsolutePath() + "/" + custom.file.getName())); } EnderFileUtils.zipFolderContents(dir, zip); EnderFileUtils.safeDeleteDirectory(dir); } catch (IOException e) { throw new RuntimeException(e); } return this; } /** * Inserts the resource pack into the game. Enabling the resource pack will * not be required, it will load automatically. * <p> * A cache of the pack zip will be kept in "resourcepack/[pack name].zip" * where "resourcepack" is a folder at the same level as the directory passed * into the constructor. */ public void inject() { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { try { if (defaultResourcePacks == null) { defaultResourcePacks = ReflectionHelper.getPrivateValue(Minecraft.class, Minecraft.getMinecraft(), "defaultResourcePacks", "field_110449_ao", "ap"); } File dest = new File(dir.getParent() + "/resourcepack/" + zip.getName()); EnderFileUtils.safeDelete(dest); FileUtils.copyFile(zip, dest); EnderFileUtils.safeDelete(zip); writeNewFile(new File(dest.getParent() + "/readme.txt"), EnderCore.lang.localize("resourcepack.readme") + "\n\n" + EnderCore.lang.localize("resourcepack.readme2")); defaultResourcePacks.add(new FileResourcePack(dest)); } catch (Exception e) { EnderCore.logger.error("Failed to inject resource pack for mod {}", modid, e); } } else { EnderCore.logger.info("Skipping resource pack, we are on a dedicated server."); } } private void writeNewFile(File file, String defaultText) throws IOException { EnderFileUtils.safeDelete(file); file.delete(); file.getParentFile().mkdirs(); file.createNewFile(); FileWriter fw = new FileWriter(file); fw.write(defaultText); fw.flush(); fw.close(); } }
package com.github.mnicky.bible4j.storage; import hirondelle.date4j.DateTime; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.TimeZone; import com.github.mnicky.bible4j.data.BibleBook; import com.github.mnicky.bible4j.data.BibleVersion; import com.github.mnicky.bible4j.data.Bookmark; import com.github.mnicky.bible4j.data.DailyReading; import com.github.mnicky.bible4j.data.DictTerm; import com.github.mnicky.bible4j.data.Note; import com.github.mnicky.bible4j.data.Position; import com.github.mnicky.bible4j.data.Verse; import static com.github.mnicky.bible4j.storage.H2DbNaming.*; public final class H2DbBibleStorage implements BibleStorage { //FIXME update SQL queries with BIBLE_NAME /** * Connection to H2 database. */ private final Connection dbConnection; /** * Constructs new H2DbBibleStorage with specified connection to H2 database. * * @param dbConnection * conection to H2 database */ public H2DbBibleStorage(Connection dbConnection) { this.dbConnection = dbConnection; } /** * Closes this H2BibleStorage. * * @throws BibleStorageException * when H2DbBibleStorage can't be closed */ @Override public void close() throws BibleStorageException { try { this.dbConnection.close(); } catch (SQLException e) { throw new BibleStorageException("BibleStorage could not be closed", e); } } // TODO needed? private int commitUpdate(PreparedStatement st) throws SQLException { int rows = 0; Connection con = st.getConnection(); try { con.setAutoCommit(false); rows = st.executeUpdate(); con.commit(); } catch (SQLException e) { if (con != null) con.rollback(); throw e; } finally { if (con != null) con.setAutoCommit(true); st.close(); } return rows; } // TODO needed? // TODO use CachedRowSet instead of ResultSet ? private ResultSet commitQuery(PreparedStatement st) throws SQLException { ResultSet result = null; Connection con = st.getConnection(); try { con.setAutoCommit(false); result = st.executeQuery(); con.commit(); } catch (SQLException e) { if (con != null) con.rollback(); result = null; throw e; } finally { if (con != null) con.setAutoCommit(true); } return result; } private int[] commitBatch(Statement st) throws SQLException { int[] rows = null; Connection con = st.getConnection(); try { con.setAutoCommit(false); rows = st.executeBatch(); con.commit(); } catch (SQLException e) { if (con != null) con.rollback(); throw e; } finally { if (con != null) con.setAutoCommit(true); st.close(); } return rows; } private boolean tableExists(String tableName) throws SQLException { ResultSet rs = null; PreparedStatement st = null; int count = 0; try { st = dbConnection .prepareStatement("SELECT COUNT(`TABLE_NAME`) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'PUBLIC' AND `TABLE_NAME` = ?"); st.setString(1, tableName); rs = commitQuery(st); while (rs.next()) count = rs.getInt(1); } finally { if (rs != null) rs.close(); if (st != null) st.close(); } return (count > 0); } @Override public int[] createStorage() throws BibleStorageException { int[] columns; try { if (tableExists("BIBLE_VERSIONS")) return null; Statement st = dbConnection.createStatement(); // FIXME add CASCADE or RESTRICTED to foreign keys etc? // TODO convert more VARCHARs to V_IGNORECASE? // TODO add more UNIQUE constraints, CHECK etc... ? st.addBatch("CREATE ALIAS IF NOT EXISTS FT_INIT FOR \"org.h2.fulltext.FullText.init\";CALL FT_INIT();"); st.addBatch("CREATE TABLE IF NOT EXISTS " + VERSIONS + " (" + VERSION_ID + " INT IDENTITY NOT NULL," + VERSION_ABBR + " VARCHAR_IGNORECASE(50) NOT NULL UNIQUE," + VERSION_NAME + " VARCHAR_IGNORECASE(50) NOT NULL," + VERSION_LANG + " VARCHAR(50) NOT NULL)"); st.addBatch("CREATE TABLE IF NOT EXISTS " + BOOKS + " (" + BOOK_ID + " INT IDENTITY NOT NULL," + BOOK_NAME + " VARCHAR_IGNORECASE(50) NOT NULL UNIQUE," + BOOK_DEUT + " BOOLEAN NOT NULL)"); st.addBatch("CREATE TABLE IF NOT EXISTS " + COORDS + " (" + COORD_ID + " INT IDENTITY NOT NULL," + COORD_BOOK + " INT NOT NULL," + COORD_CHAPT + " INT NOT NULL," + COORD_VERSE + " INT NOT NULL," + "CONSTRAINT `coords_unique` UNIQUE ( " + COORD_BOOK + ", " + COORD_CHAPT + ", " + COORD_VERSE + ")," + "FOREIGN KEY (" + COORD_BOOK + ") REFERENCES " + BOOKS + ")"); st.addBatch("CREATE TABLE IF NOT EXISTS " + VERSES + " (" + VERSE_ID + " INT IDENTITY NOT NULL," + VERSE_TEXT + " VARCHAR(4096) NOT NULL," + VERSE_VERSION + " INT NOT NULL," + VERSE_COORD + " INT NOT NULL," + "FOREIGN KEY (" + VERSE_VERSION + ") REFERENCES " + VERSIONS + "," + "FOREIGN KEY (" + VERSE_COORD + ") REFERENCES " + COORDS + ")"); st.addBatch("CREATE TABLE IF NOT EXISTS " + NOTES + " (" + NOTE_ID + " INT IDENTITY NOT NULL," + NOTE_TYPE + " VARCHAR(1) NOT NULL," + NOTE_TEXT + " VARCHAR(500) NOT NULL," + NOTE_COORD + " INT NOT NULL," + "FOREIGN KEY (" + NOTE_COORD + ") REFERENCES " + COORDS + ")"); st.addBatch("CREATE TABLE IF NOT EXISTS " + BKMARKS + " (" + BKMARK_ID + " INT IDENTITY NOT NULL," + BKMARK_NAME + " VARCHAR(50) NOT NULL," + BKMARK_VERSE + " INT NOT NULL," + "FOREIGN KEY (" + BKMARK_VERSE + ") REFERENCES " + VERSES + ")"); st.addBatch("CREATE TABLE IF NOT EXISTS " + RLISTS + " (" + RLIST_ID + " INT IDENTITY NOT NULL," + RLIST_NAME + " VARCHAR(50) NOT NULL UNIQUE)"); st.addBatch("CREATE TABLE IF NOT EXISTS " + READS + " (" + READ_ID + " INT IDENTITY NOT NULL," + READ_DATE + " DATE NOT NULL," + READ_LIST + " INT NOT NULL," + "FOREIGN KEY (" + READ_LIST + ") REFERENCES " + RLISTS + ")"); st.addBatch("CREATE TABLE IF NOT EXISTS " + READxCOORDS + " (" + READxCOORD_ID + " INT IDENTITY NOT NULL," + READxCOORD_COORD + " INT NOT NULL," + READxCOORD_READ + " INT NOT NULL," + "FOREIGN KEY (" + READxCOORD_COORD + ") REFERENCES " + COORDS + "," + "FOREIGN KEY (" + READxCOORD_READ + ") REFERENCES " + READS + ")"); st.addBatch("CREATE TABLE IF NOT EXISTS " + TERMS + " (" + TERM_ID + " INT IDENTITY NOT NULL," + TERM_NAME + " VARCHAR(50) NOT NULL UNIQUE," + TERM_DEF + " VARCHAR(500) NOT NULL)"); // TODO make constants from strings st.addBatch("CALL FT_CREATE_INDEX('PUBLIC', 'VERSES', 'TEXT');"); columns = commitBatch(st); } catch (SQLException e) { throw new BibleStorageException("BibleStorage could not be created", e); } return columns; } @Override public void insertVerse(Verse verse) throws BibleStorageException { try { PreparedStatement st = dbConnection .prepareStatement("INSERT INTO " + VERSES + " (" + VERSE_TEXT + ", " + VERSE_VERSION + ", " + VERSE_COORD + ") VALUES " + "( ?," + "(SELECT DISTINCT " + VERSION_ID_F + " FROM " + VERSIONS + " WHERE " + VERSION_ABBR_F + " = ?)," + "(SELECT DISTINCT " + COORD_ID_F + " FROM " + COORDS + " WHERE " + COORD_CHAPT_F + " = ? AND " + COORD_BOOK_F + " = (SELECT DISTINCT " + BOOK_ID_F + " FROM " + BOOKS + " WHERE " + BOOK_NAME_F + " = ?) AND " + COORD_VERSE_F + " = ? ))"); st.setString(1, verse.getText()); st.setString(2, verse.getBibleVersion().getAbbr()); st.setInt(3, verse.getPosition().getChapterNum()); st.setString(4, verse.getPosition().getBook().getName()); st.setInt(5, verse.getPosition().getVerseNum()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Verse could not be inserted", e); } } @Override public void insertBibleBook(BibleBook book) throws BibleStorageException { try { PreparedStatement st = dbConnection.prepareStatement("MERGE INTO " + BOOKS + "(" + BOOK_NAME + ", " + BOOK_DEUT + ") KEY (" + BOOK_NAME + ") VALUES ( ?, ?)"); st.setString(1, book.getName()); st.setBoolean(2, book.isDeutero()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Bible book could not be inserted", e); } } @Override public void insertPosition(Position position) throws BibleStorageException { try { PreparedStatement st = dbConnection .prepareStatement("MERGE INTO " + COORDS + "(" + COORD_BOOK + ", " + COORD_CHAPT + ", " + COORD_VERSE + ")" + " KEY ( " + COORD_BOOK + ", " + COORD_CHAPT + ", " + COORD_VERSE + ")" + " VALUES ((SELECT DISTINCT " + BOOK_ID_F + " FROM " + BOOKS + " WHERE " + BOOK_NAME_F + " = ?), ?, ?)"); st.setString(1, position.getBook().getName()); st.setInt(2, position.getChapterNum()); st.setInt(3, position.getVerseNum()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Position could not be inserted", e); } } @Override public void insertBibleVersion(BibleVersion version) throws BibleStorageException { try { PreparedStatement st = dbConnection.prepareStatement("MERGE INTO " + VERSIONS + " (" + VERSION_ABBR + ", " + VERSION_LANG + ", " + VERSION_NAME + ") KEY ( " + VERSION_ABBR + " ) VALUES ( ?, ?, ?)"); st.setString(1, version.getAbbr()); st.setString(2, version.getLanguage()); st.setString(3, version.getName()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Bible version could not be inserted", e); } } @Override public BibleVersion getBibleVersion(String abbr) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; BibleVersion version = null; try { st = dbConnection .prepareStatement("SELECT " + VERSION_NAME_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + "FROM " + VERSIONS + "WHERE " + VERSION_ABBR_F + " = ? LIMIT 1"); st.setString(1, abbr.toLowerCase(new Locale("en"))); rs = commitQuery(st); while (rs.next()) version = new BibleVersion(rs.getString(1), rs.getString(2), rs.getString(3)); } catch (SQLException e) { throw new BibleStorageException("Version could not be retrieved", e); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return version; } @Override public List<BibleVersion> getAllBibleVersions() throws BibleStorageException { PreparedStatement st = null; List<BibleVersion> versionList = new ArrayList<BibleVersion>(); try { st = dbConnection .prepareStatement("SELECT " + VERSION_NAME_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + "FROM " + VERSIONS + "ORDER BY " + VERSION_ID_F); ResultSet rs = commitQuery(st); while (rs.next()) versionList.add(new BibleVersion(rs.getString(1), rs.getString(2), rs.getString(3))); rs.close(); } catch (SQLException e) { throw new BibleStorageException("Bible versions could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return versionList; } @Override public Verse getVerse(Position position, BibleVersion version) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; Verse verse = null; try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + VERSIONS + "INNER JOIN " + VERSES + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " " + "WHERE " + COORD_CHAPT_F + " = ? AND " + BOOK_NAME_F + " = ? AND " + VERSION_ABBR_F + " = ? AND " + COORD_VERSE_F + " = ? LIMIT 1"); st.setInt(1, position.getChapterNum()); st.setString(2, position.getBook().getName()); st.setString(3, version.getAbbr()); st.setInt(4, position.getVerseNum()); rs = commitQuery(st); while (rs.next()) verse = new Verse(rs.getString(1), new Position(BibleBook.getBibleBookByName(rs .getString(6)), rs.getInt(5), rs.getInt(4)), new BibleVersion(rs.getString(2), rs.getString(3))); } catch (SQLException e) { throw new BibleStorageException("Verse could not be retrieved", e); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verse; } @Override public List<Verse> getVerses(List<Position> positions, BibleVersion version) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); for (Position position : positions) { try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + VERSIONS + "INNER JOIN " + VERSES + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " " + "WHERE " + COORD_CHAPT_F + " = ? AND " + BOOK_NAME_F + " = ? AND " + VERSION_ABBR_F + " = ? AND " + COORD_VERSE_F + " = ? LIMIT 1"); st.setInt(1, position.getChapterNum()); st.setString(2, position.getBook().getName()); st.setString(3, version.getAbbr()); st.setInt(4, position.getVerseNum()); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } } return verseList; } //chapter is represented by Position object with ignored verse number information @Override public List<Verse> getChapter(Position chapter, BibleVersion version) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + VERSIONS + "INNER JOIN " + VERSES + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " " + "WHERE " + COORD_CHAPT_F + " = ? AND " + BOOK_NAME_F + " = ? AND " + VERSION_ABBR_F + " = ?"); st.setInt(1, chapter.getChapterNum()); st.setString(2, chapter.getBook().getName()); st.setString(3, version.getAbbr()); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verseList; } @Override public List<Position> getChapterList(BibleVersion version) throws BibleStorageException { PreparedStatement st = null; List<Position> chapterList = new ArrayList<Position>(); try { st = dbConnection .prepareStatement("SELECT DISTINCT " + BOOK_NAME_F + ", " + COORD_CHAPT_F + "FROM " + VERSIONS + "INNER JOIN " + VERSES + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " " + "WHERE " + VERSION_ABBR_F + " = ?"); st.setString(1, version.getAbbr()); ResultSet rs = commitQuery(st); while (rs.next()) chapterList.add(new Position(BibleBook.getBibleBookByName(rs.getString(1)), rs.getInt(2), 0)); rs.close(); } catch (SQLException e) { throw new BibleStorageException("Chapters could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } Collections.sort(chapterList); return chapterList; } @Override public List<Verse> compareVerses(Position position, List<BibleVersion> versions) throws BibleStorageException { PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + VERSIONS + "INNER JOIN " + VERSES + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " " + "WHERE " + COORD_CHAPT_F + " = ? AND " + BOOK_NAME_F + " = ? AND " + VERSION_ABBR_F + " = ? AND " + COORD_VERSE_F + " = ? LIMIT 1"); for (BibleVersion version : versions) { st.setInt(1, position.getChapterNum()); st.setString(2, position.getBook().getName()); st.setString(3, version.getAbbr()); st.setInt(4, position.getVerseNum()); ResultSet rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); rs.close(); } } catch (SQLException e) { throw new BibleStorageException("Verses could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verseList; } @Override public List<Verse> compareVerses(List<Position> positions, List<BibleVersion> versions) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); for (BibleVersion version : versions) { for (Position position : positions) { try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + VERSIONS + "INNER JOIN " + VERSES + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " " + "WHERE " + COORD_CHAPT_F + " = ? AND " + BOOK_NAME_F + " = ? AND " + VERSION_ABBR_F + " = ? AND " + COORD_VERSE_F + " = ? LIMIT 1"); st.setInt(1, position.getChapterNum()); st.setString(2, position.getBook().getName()); st.setString(3, version.getAbbr()); st.setInt(4, position.getVerseNum()); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return verseList; } @Override public void insertBookmark(Bookmark bookmark) throws BibleStorageException { try { PreparedStatement st = dbConnection.prepareStatement( "INSERT INTO " + BKMARKS + "(" + BKMARK_VERSE + ", " + BKMARK_NAME + ") VALUES" + "((SELECT DISTINCT " + VERSE_ID_F + " FROM " + VERSES + " WHERE " + VERSE_VERSION_F + " = (SELECT DISTINCT " + VERSION_ID_F + " FROM " + VERSIONS + " WHERE " + VERSION_ABBR_F + " = ? AND " + VERSION_LANG_F + " = ?) AND " + VERSE_COORD_F + " = (SELECT DISTINCT " + COORD_ID_F + " FROM " + COORDS + " WHERE" + COORD_BOOK_F + " = (SELECT DISTINCT " + BOOK_ID_F + " FROM " + BOOKS + " WHERE " + BOOK_NAME_F + " = ?) AND " + COORD_CHAPT_F + " = ? AND " + COORD_VERSE_F + " = ?) AND " + VERSE_TEXT_F + " = ?)" + ", ?)"); st.setString(1, bookmark.getVerse().getBibleVersion().getAbbr()); st.setString(2, bookmark.getVerse().getBibleVersion().getLanguage()); st.setString(3, bookmark.getVerse().getPosition().getBook().getName()); st.setInt(4, bookmark.getVerse().getPosition().getChapterNum()); st.setInt(5, bookmark.getVerse().getPosition().getVerseNum()); st.setString(6, bookmark.getVerse().getText()); st.setString(7, bookmark.getName()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Bookmark could not be inserted", e); } } @Override public List<Bookmark> getBookmarks() throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Bookmark> bookmarkList = new ArrayList<Bookmark>(); try { st = dbConnection .prepareStatement("SELECT " + BKMARK_NAME_F + ", " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + BKMARKS + "INNER JOIN " + VERSES + " ON " + BKMARK_VERSE_F + " = " + VERSE_ID_F + " " + "INNER JOIN " + VERSIONS + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F); rs = commitQuery(st); while (rs.next()) bookmarkList.add(new Bookmark(rs.getString(1), new Verse(rs.getString(2), new Position(BibleBook .getBibleBookByName(rs .getString(7)), rs .getInt(6), rs .getInt(5)), new BibleVersion(rs.getString(3), rs .getString(4))))); } catch (SQLException e) { throw new BibleStorageException("Bookmarks could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return bookmarkList; } @Override public List<Bookmark> getBookmarks(BibleVersion version) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Bookmark> bookmarkList = new ArrayList<Bookmark>(); try { st = dbConnection .prepareStatement("SELECT " + BKMARK_NAME_F + ", " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + "FROM " + BKMARKS + "INNER JOIN " + VERSES + " ON " + BKMARK_VERSE_F + " = " + VERSE_ID_F + " " + "INNER JOIN " + VERSIONS + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + "INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + "WHERE " + VERSION_ABBR_F + " = ?"); st.setString(1, version.getAbbr()); rs = commitQuery(st); while (rs.next()) bookmarkList.add(new Bookmark(rs.getString(1), new Verse(rs.getString(2), new Position(BibleBook .getBibleBookByName(rs .getString(7)), rs .getInt(6), rs .getInt(5)), new BibleVersion(rs.getString(3), rs .getString(4))))); } catch (SQLException e) { throw new BibleStorageException("Bookmarks could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return bookmarkList; } @Override public void insertNote(Note note) throws BibleStorageException { try { PreparedStatement st = dbConnection.prepareStatement( "INSERT INTO " + NOTES + "(" + NOTE_TYPE + ", " + NOTE_TEXT + ", " + NOTE_COORD + ") VALUES" + "(?, ?, (SELECT DISTINCT " + COORD_ID_F + " FROM " + COORDS + " WHERE" + COORD_BOOK_F + " = (SELECT DISTINCT " + BOOK_ID_F + " FROM " + BOOKS + " WHERE " + BOOK_NAME_F + " = ?) AND " + COORD_CHAPT_F + " = ? AND " + COORD_VERSE_F + " = ?))"); st.setString(1, Character.toString(note.getType().getSpecifyingChar())); st.setString(2, note.getText()); st.setString(3, note.getPosition().getBook().getName()); st.setInt(4, note.getPosition().getChapterNum()); st.setInt(5, note.getPosition().getVerseNum()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Note could not be inserted", e); } } @Override public List<Note> getNotes(Position position) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Note> noteList = new ArrayList<Note>(); try { st = dbConnection .prepareStatement("SELECT " + NOTE_TEXT_F + ", " + BOOK_NAME_F + ", " + COORD_CHAPT_F + ", " + COORD_VERSE_F + ", " + NOTE_TYPE_F + "FROM " + NOTES + "INNER JOIN " + COORDS + " ON " + NOTE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + "WHERE " + BOOK_NAME_F + " = ? AND " + COORD_CHAPT_F + " = ? AND " + COORD_VERSE_F + "= ?"); st.setString(1, position.getBook().getName()); st.setInt(2, position.getChapterNum()); st.setInt(3, position.getVerseNum()); rs = commitQuery(st); while (rs.next()) noteList.add(new Note(rs.getString(1), new Position(BibleBook.getBibleBookByName(rs.getString(2)), rs .getInt(3), rs.getInt(4)), Note.getNoteTypeByChar(rs .getString(5).charAt(0)))); } catch (SQLException e) { throw new BibleStorageException("Notes could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return noteList; } //TODO add unit test @Override public List<Note> getNotesForChapter(Position chapter) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Note> noteList = new ArrayList<Note>(); try { st = dbConnection .prepareStatement("SELECT " + NOTE_TEXT_F + ", " + BOOK_NAME_F + ", " + COORD_CHAPT_F + ", " + COORD_VERSE_F + ", " + NOTE_TYPE_F + "FROM " + NOTES + "INNER JOIN " + COORDS + " ON " + NOTE_COORD_F + " = " + COORD_ID_F + " " + "INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + "WHERE " + BOOK_NAME_F + " = ? AND " + COORD_CHAPT_F + " = ?"); st.setString(1, chapter.getBook().getName()); st.setInt(2, chapter.getChapterNum()); rs = commitQuery(st); while (rs.next()) noteList.add(new Note(rs.getString(1), new Position(BibleBook.getBibleBookByName(rs.getString(2)), rs .getInt(3), rs.getInt(4)), Note.getNoteTypeByChar(rs .getString(5).charAt(0)))); } catch (SQLException e) { throw new BibleStorageException("Notes could not be retrieved", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return noteList; } @Override public void insertDictTerm(DictTerm term) throws BibleStorageException { try { PreparedStatement st = dbConnection.prepareStatement( "MERGE INTO " + TERMS + "(" + TERM_NAME + ", " + TERM_DEF + ") KEY (" + TERM_NAME + ") VALUES (?, ?)"); st.setString(1, term.getName()); st.setString(2, term.getDefinition()); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("DictTerm could not be inserted", e); } } @Override public DictTerm getDictTerm(String name) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; DictTerm term = null; try { st = dbConnection .prepareStatement("SELECT " + TERM_NAME_F + ", " + TERM_DEF_F + "FROM " + TERMS + "WHERE " + TERM_NAME_F + " = ? LIMIT 1"); st.setString(1, name); rs = commitQuery(st); while (rs.next()) term = new DictTerm(rs.getString(1), rs.getString(2)); } catch (SQLException e) { throw new BibleStorageException("DictTerm could not be retrieved", e); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return term; } @Override public void insertReadingList(String name) throws BibleStorageException { try { PreparedStatement st = dbConnection.prepareStatement( "MERGE INTO " + RLISTS + "(" + RLIST_NAME + ") KEY (" + RLIST_NAME + ") VALUES (?)"); st.setString(1, name); commitUpdate(st); } catch (SQLException e) { throw new BibleStorageException("Reading list could not be inserted", e); } } // TODO refactor this method @Override public void insertDailyReading(DailyReading reading) throws BibleStorageException { PreparedStatement st = null; try { dbConnection.setAutoCommit(false); // insert reading st = dbConnection.prepareStatement( "INSERT INTO " + READS + "(" + READ_DATE + ", " + READ_LIST + ") VALUES (?, " + "(SELECT DISTINCT " + RLIST_ID_F + " FROM " + RLISTS + "WHERE " + RLIST_NAME_F + " = ?))"); st.setDate(1, new Date(reading.getDate().getMilliseconds(TimeZone.getDefault()))); st.setString(2, reading.getReadingListName()); st.executeUpdate(); // insert verses of this reading int readingId = getThisReadingId(reading); st = dbConnection.prepareStatement("INSERT INTO " + READxCOORDS + "(" + READxCOORD_COORD + ", " + READxCOORD_READ + ") VALUES (" + "(SELECT DISTINCT " + COORD_ID_F + " FROM " + COORDS + " WHERE" + COORD_BOOK_F + " = (SELECT DISTINCT " + BOOK_ID_F + " FROM " + BOOKS + " WHERE " + BOOK_NAME_F + " = ?) AND " + COORD_CHAPT_F + " = ? AND " + COORD_VERSE_F + " = ?), ?)"); for (Position p : reading.getPositions()) { st.setString(1, p.getBook().name()); st.setInt(2, p.getChapterNum()); st.setInt(3, p.getVerseNum()); st.setInt(4, readingId); st.addBatch(); } st.executeBatch(); dbConnection.commit(); } catch (SQLException e) { try { dbConnection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new BibleStorageException("DailyReading could not be inserted", e); } finally { try { dbConnection.setAutoCommit(true); if (st != null) st.close(); } catch (SQLException e2) { e2.printStackTrace(); } } } private int getThisReadingId(DailyReading reading) throws BibleStorageException, SQLException { ResultSet rs = null; PreparedStatement st = null; int readingId = 0; try { st = dbConnection .prepareStatement("SELECT " + READ_ID_F + "FROM " + READS + "WHERE " + READ_DATE_F + " = ? AND " + READ_LIST_F + " = (SELECT DISTINCT " + RLIST_ID_F + " FROM " + RLISTS + " WHERE " + RLIST_NAME_F + " = ?) LIMIT 1"); st.setDate(1, new Date(reading.getDate().getMilliseconds(TimeZone.getTimeZone("GMT")))); st.setString(2, reading.getReadingListName()); rs = commitQuery(st); while (rs.next()) readingId = rs.getInt(1); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return readingId; } @Override public List<DailyReading> getDailyReadings(DateTime date) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<DailyReading> readings = new ArrayList<DailyReading>(); try { st = dbConnection .prepareStatement("SELECT " + RLIST_NAME_F + ", " + READ_DATE_F + ", " + BOOK_NAME_F + ", " + COORD_CHAPT_F + ", " + COORD_VERSE_F + " FROM " + RLISTS + " INNER JOIN " + READS + " ON " + READ_LIST_F + " = " + RLIST_ID_F + " INNER JOIN " + READxCOORDS + " ON " + READxCOORD_READ_F + " = " + READ_ID_F + " INNER JOIN " + COORDS + " ON " + COORD_ID_F + " = " + READxCOORD_COORD_F + " INNER JOIN " + BOOKS + " ON " + BOOK_ID_F + " = " + COORD_BOOK_F + " WHERE " + READ_DATE_F + " = ? ORDER BY " + RLIST_NAME_F); st.setDate(1, new Date(date.getMilliseconds(TimeZone.getDefault()))); rs = commitQuery(st); String lastReadingListName = ""; DateTime lastRecDate = null; List<Position> positions = new ArrayList<Position>(); while (rs.next()) { String readingListName = rs.getString(1); DateTime recDate = DateTime.forInstant(rs.getDate(2).getTime(), TimeZone.getDefault()); BibleBook book = BibleBook.getBibleBookByName(rs.getString(3)); int chapterNum = rs.getInt(4); int verseNum = rs.getInt(5); if (lastReadingListName.equals("") || lastReadingListName.equals(readingListName)) { positions.add(new Position(book, chapterNum, verseNum)); } else { readings.add(new DailyReading(lastReadingListName, lastRecDate, positions)); positions = new ArrayList<Position>(); positions.add(new Position(book, chapterNum, verseNum)); } lastReadingListName = readingListName; lastRecDate = recDate; if (rs.isLast()) { readings.add(new DailyReading(lastReadingListName, lastRecDate, positions)); } } } catch (SQLException e) { throw new BibleStorageException("DailyReadings could not be retrieved", e); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return readings; } @Override public List<Verse> searchVersesForText(String text) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + " FROM FT_SEARCH_DATA(?, 0, 0) FT" + " INNER JOIN " + VERSES + " ON FT.TABLE = 'VERSES' AND " + VERSE_ID_F + " = FT.KEYS[0]" + " INNER JOIN " + VERSIONS + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " " + " INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " " + " INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " ORDER BY" + VERSION_ABBR_F); st.setString(1, text); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be searched", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verseList; } //TODO add unit test @Override public List<Verse> searchVersesForText(String text, BibleVersion version) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + " FROM FT_SEARCH_DATA(?, 0, 0) FT" + " INNER JOIN " + VERSES + " ON FT.TABLE = 'VERSES' AND " + VERSE_ID_F + " = FT.KEYS[0]" + " INNER JOIN " + VERSIONS + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " AND" + VERSION_ABBR_F + " = ?" + " INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " ORDER BY" + VERSION_ABBR_F); st.setString(1, text); st.setString(2, version.getAbbr()); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be searched", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verseList; } //TODO add unit test @Override public List<Verse> searchVersesForText(String text, BibleBook book) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + " FROM FT_SEARCH_DATA(?, 0, 0) FT" + " INNER JOIN " + VERSES + " ON FT.TABLE = 'VERSES' AND " + VERSE_ID_F + " = FT.KEYS[0]" + " INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " AND" + BOOK_NAME_F + " = ?" + " INNER JOIN " + VERSIONS + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " ORDER BY" + VERSION_ABBR_F); st.setString(1, text); st.setString(2, book.getName()); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be searched", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verseList; } //TODO add unit test @Override public List<Verse> searchVersesForText(String text, BibleBook book, BibleVersion version) throws BibleStorageException { ResultSet rs = null; PreparedStatement st = null; List<Verse> verseList = new ArrayList<Verse>(); try { st = dbConnection .prepareStatement("SELECT " + VERSE_TEXT_F + ", " + VERSION_ABBR_F + ", " + VERSION_LANG_F + ", " + COORD_VERSE_F + ", " + COORD_CHAPT_F + ", " + BOOK_NAME_F + " FROM FT_SEARCH_DATA(?, 0, 0) FT" + " INNER JOIN " + VERSES + " ON FT.TABLE = 'VERSES' AND " + VERSE_ID_F + " = FT.KEYS[0]" + " INNER JOIN " + COORDS + " ON " + VERSE_COORD_F + " = " + COORD_ID_F + " INNER JOIN " + BOOKS + " ON " + COORD_BOOK_F + " = " + BOOK_ID_F + " AND" + BOOK_NAME_F + " = ?" + " INNER JOIN " + VERSIONS + " ON " + VERSE_VERSION_F + " = " + VERSION_ID_F + " AND" + VERSION_ABBR_F + " = ?" + " ORDER BY" + VERSION_ABBR_F); st.setString(1, text); st.setString(2, book.getName()); st.setString(3, version.getAbbr()); rs = commitQuery(st); while (rs.next()) verseList.add(new Verse(rs.getString(1), new Position(BibleBook .getBibleBookByName(rs .getString(6)), rs.getInt(5), rs .getInt(4)), new BibleVersion(rs.getString(2), rs .getString(3)))); } catch (SQLException e) { throw new BibleStorageException("Verses could not be searched", e); } finally { try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } } return verseList; } }
package com.github.rnewson.couchdb.lucene.couchdb; import java.io.IOException; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import com.github.rnewson.couchdb.lucene.util.Utils; public final class Database { private final HttpClient httpClient; private final String url; public Database(final HttpClient httpClient, final String url) { this.httpClient = httpClient; this.url = url.endsWith("/") ? url : url + "/"; } public boolean create() throws IOException { return HttpUtils.put(httpClient, url, null) == 201; } public boolean delete() throws IOException { return HttpUtils.delete(httpClient, url) == 200; } public JSONArray getAllDesignDocuments() throws IOException { return getDocuments("_design", "_design0").getJSONArray("rows"); } public JSONObject getDocument(final String id) throws IOException { final String response = HttpUtils.get(httpClient, url + Utils.urlEncode(id)); return JSONObject.fromObject(response); } public JSONObject getDocuments(final String... ids) throws IOException { final JSONArray keys = new JSONArray(); for (final String id : ids) { keys.add(id); } final JSONObject req = new JSONObject(); req.element("keys", keys); final String response = HttpUtils.post(httpClient, url + "_all_docs?include_docs=true", req.toString()); return JSONObject.fromObject(response); } public JSONObject getDocuments(final String startkey, final String endkey) throws IOException { return JSONObject.fromObject(HttpUtils.get(httpClient, String.format( "%s_all_docs?startkey=%%22%s%%22&endkey=%%22%s%%22&include_docs=true", url, Utils.urlEncode(startkey), Utils .urlEncode(endkey)))); } public JSONObject getInfo() throws IOException { return JSONObject.fromObject(HttpUtils.get(httpClient, url)); } public <T> T handleAttachment(final String doc, final String att, final ResponseHandler<T> handler) throws IOException { final HttpGet get = new HttpGet(url + "/" + Utils.urlEncode(doc) + "/" + Utils.urlEncode(att)); return httpClient.execute(get, handler); } public HttpUriRequest getChangesRequest(final long since) throws IOException { return new HttpGet(url + "_changes?feed=continuous&heartbeat=15000&include_docs=true&since=" + since); } public boolean saveDocument(final String id, final String body) throws IOException { return HttpUtils.put(httpClient, url + Utils.urlEncode(id), body) == 201; } }
package com.gmail.trentech.wirelessred.utils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.ConcurrentHashMap; import org.spongepowered.api.item.ItemTypes; import com.gmail.trentech.wirelessred.Main; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; public class ConfigManager { private Path path; private CommentedConfigurationNode config; private ConfigurationLoader<CommentedConfigurationNode> loader; private static ConcurrentHashMap<String, ConfigManager> configManagers = new ConcurrentHashMap<>(); private ConfigManager(String configName) { try { path = Main.instance().getPath().resolve(configName + ".conf"); if (!Files.exists(path)) { Files.createFile(path); Main.instance().getLog().info("Creating new " + path.getFileName() + " file..."); } } catch (IOException e) { e.printStackTrace(); } load(); } public static ConfigManager get(String configName) { return configManagers.get(configName); } public static ConfigManager get() { return configManagers.get("config"); } public static ConfigManager init() { return init("config"); } public static ConfigManager init(String configName) { ConfigManager configManager = new ConfigManager(configName); CommentedConfigurationNode config = configManager.getConfig(); if (configName.equalsIgnoreCase("config")) { if (config.getNode("settings", "starting_range").isVirtual()) { config.getNode("settings", "starting_range").setValue("32"); } if (config.getNode("settings", "economy").isVirtual()) { config.getNode("settings", "economy", "items", "tool").setValue(50.0); config.getNode("settings", "economy", "items", "transmitter").setValue(50.0); config.getNode("settings", "economy", "items", "receiver").setValue(50.0); config.getNode("settings", "economy", "items", "upgrade_64").setValue(50.0); config.getNode("settings", "economy", "items", "upgrade_128").setValue(100.0); config.getNode("settings", "economy", "items", "upgrade_256").setValue(150.0); config.getNode("settings", "economy", "items", "upgrade_512").setValue(175.0); config.getNode("settings", "economy", "items", "upgrade_unlimited").setValue(200.0); config.getNode("settings", "economy", "enable").setValue(true); } if (config.getNode("recipes", "tool").isVirtual()) { config.getNode("recipes", "tool", "grid_size").setValue("2x2"); config.getNode("recipes", "tool", "1x1").setValue(ItemTypes.REDSTONE.getId()); config.getNode("recipes", "tool", "1x2").setValue(ItemTypes.NONE.getId()); config.getNode("recipes", "tool", "2x1").setValue(ItemTypes.NONE.getId()); config.getNode("recipes", "tool", "2x2").setValue(ItemTypes.STICK.getId()); } if (config.getNode("recipes", "receiver").isVirtual()) { config.getNode("recipes", "receiver", "grid_size").setValue("3x3"); config.getNode("recipes", "receiver", "1x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "receiver", "1x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "receiver", "1x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "receiver", "2x1").setValue(ItemTypes.REDSTONE.getId()); config.getNode("recipes", "receiver", "2x2").setValue(ItemTypes.REPEATER.getId()); config.getNode("recipes", "receiver", "2x3").setValue(ItemTypes.REDSTONE.getId()); config.getNode("recipes", "receiver", "3x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "receiver", "3x2").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "receiver", "3x3").setValue(ItemTypes.GOLD_INGOT.getId()); } if (config.getNode("recipes", "transmitter").isVirtual()) { config.getNode("recipes", "transmitter", "grid_size").setValue("3x3"); config.getNode("recipes", "transmitter", "1x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "transmitter", "1x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "transmitter", "1x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "transmitter", "2x1").setValue(ItemTypes.REDSTONE.getId()); config.getNode("recipes", "transmitter", "2x2").setValue(ItemTypes.COMPARATOR.getId()); config.getNode("recipes", "transmitter", "2x3").setValue(ItemTypes.REDSTONE.getId()); config.getNode("recipes", "transmitter", "3x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "transmitter", "3x2").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "transmitter", "3x3").setValue(ItemTypes.GOLD_INGOT.getId()); } if (config.getNode("recipes", "upgrade_64").isVirtual()) { config.getNode("recipes", "upgrade_64", "grid_size").setValue("3x3"); config.getNode("recipes", "upgrade_64", "1x1").setValue(ItemTypes.STONE.getId()); config.getNode("recipes", "upgrade_64", "1x2").setValue(ItemTypes.STONE.getId()); config.getNode("recipes", "upgrade_64", "1x3").setValue(ItemTypes.STONE.getId()); config.getNode("recipes", "upgrade_64", "2x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_64", "2x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "upgrade_64", "2x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_64", "3x1").setValue(ItemTypes.STONE.getId()); config.getNode("recipes", "upgrade_64", "3x2").setValue(ItemTypes.STONE.getId()); config.getNode("recipes", "upgrade_64", "3x3").setValue(ItemTypes.STONE.getId()); } if (config.getNode("recipes", "upgrade_128").isVirtual()) { config.getNode("recipes", "upgrade_128", "grid_size").setValue("3x3"); config.getNode("recipes", "upgrade_128", "1x1").setValue(ItemTypes.IRON_INGOT.getId()); config.getNode("recipes", "upgrade_128", "1x2").setValue(ItemTypes.IRON_INGOT.getId()); config.getNode("recipes", "upgrade_128", "1x3").setValue(ItemTypes.IRON_INGOT.getId()); config.getNode("recipes", "upgrade_128", "2x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_128", "2x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "upgrade_128", "2x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_128", "3x1").setValue(ItemTypes.IRON_INGOT.getId()); config.getNode("recipes", "upgrade_128", "3x2").setValue(ItemTypes.IRON_INGOT.getId()); config.getNode("recipes", "upgrade_128", "3x3").setValue(ItemTypes.IRON_INGOT.getId()); } if (config.getNode("recipes", "upgrade_256").isVirtual()) { config.getNode("recipes", "upgrade_256", "grid_size").setValue("3x3"); config.getNode("recipes", "upgrade_256", "1x1").setValue(ItemTypes.IRON_BLOCK.getId()); config.getNode("recipes", "upgrade_256", "1x2").setValue(ItemTypes.IRON_BLOCK.getId()); config.getNode("recipes", "upgrade_256", "1x3").setValue(ItemTypes.IRON_BLOCK.getId()); config.getNode("recipes", "upgrade_256", "2x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_256", "2x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "upgrade_256", "2x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_256", "3x1").setValue(ItemTypes.IRON_BLOCK.getId()); config.getNode("recipes", "upgrade_256", "3x2").setValue(ItemTypes.IRON_BLOCK.getId()); config.getNode("recipes", "upgrade_256", "3x3").setValue(ItemTypes.IRON_BLOCK.getId()); } if (config.getNode("recipes", "upgrade_512").isVirtual()) { config.getNode("recipes", "upgrade_512", "grid_size").setValue("3x3"); config.getNode("recipes", "upgrade_512", "1x1").setValue(ItemTypes.DIAMOND.getId()); config.getNode("recipes", "upgrade_512", "1x2").setValue(ItemTypes.DIAMOND.getId()); config.getNode("recipes", "upgrade_512", "1x3").setValue(ItemTypes.DIAMOND.getId()); config.getNode("recipes", "upgrade_512", "2x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_512", "2x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "upgrade_512", "2x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_512", "3x1").setValue(ItemTypes.DIAMOND.getId()); config.getNode("recipes", "upgrade_512", "3x2").setValue(ItemTypes.DIAMOND.getId()); config.getNode("recipes", "upgrade_512", "3x3").setValue(ItemTypes.DIAMOND.getId()); } if (config.getNode("recipes", "upgrade_unlimited").isVirtual()) { config.getNode("recipes", "upgrade_unlimited", "grid_size").setValue("3x3"); config.getNode("recipes", "upgrade_unlimited", "1x1").setValue(ItemTypes.DIAMOND_BLOCK.getId()); config.getNode("recipes", "upgrade_unlimited", "1x2").setValue(ItemTypes.DIAMOND_BLOCK.getId()); config.getNode("recipes", "upgrade_unlimited", "1x3").setValue(ItemTypes.DIAMOND_BLOCK.getId()); config.getNode("recipes", "upgrade_unlimited", "2x1").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_unlimited", "2x2").setValue(ItemTypes.REDSTONE_TORCH.getId()); config.getNode("recipes", "upgrade_unlimited", "2x3").setValue(ItemTypes.GOLD_INGOT.getId()); config.getNode("recipes", "upgrade_unlimited", "3x1").setValue(ItemTypes.DIAMOND_BLOCK.getId()); config.getNode("recipes", "upgrade_unlimited", "3x2").setValue(ItemTypes.DIAMOND_BLOCK.getId()); config.getNode("recipes", "upgrade_unlimited", "3x3").setValue(ItemTypes.DIAMOND_BLOCK.getId()); } } configManager.save(); configManagers.put(configName, configManager); return configManager; } public ConfigurationLoader<CommentedConfigurationNode> getLoader() { return loader; } public CommentedConfigurationNode getConfig() { return config; } private void load() { loader = HoconConfigurationLoader.builder().setPath(path).build(); try { config = loader.load(); } catch (IOException e) { Main.instance().getLog().error("Failed to load config"); e.printStackTrace(); } } public void save() { try { loader.save(config); } catch (IOException e) { Main.instance().getLog().error("Failed to save config"); e.printStackTrace(); } } }
package com.google.common.html.plugin.js; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Set; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import com.google.common.html.plugin.Sources.Source; import com.google.common.html.plugin.common.TopoSort; import com.google.common.html.plugin.common.CommonPlanner; import com.google.common.html.plugin.common.Ingredients.FileIngredient; import com.google.common.html.plugin.common.Ingredients.FileSetIngredient; import com.google.common.html.plugin.common.Ingredients.OptionsIngredient; import com.google.common.html.plugin.common.Ingredients.PathValue; import com.google.common.html.plugin.common.Ingredients .SerializedObjectIngredient; import com.google.common.html.plugin.plan.Ingredient; import com.google.common.html.plugin.plan.PlanKey; import com.google.common.html.plugin.plan.Step; import com.google.common.html.plugin.plan.StepSource; import com.google.javascript.jscomp.Compiler; import com.google.javascript.jscomp.CompilerInput; import com.google.javascript.jscomp.SourceFile; final class ComputeJsDepGraph extends Step { final JsPlanner planner; private SerializedObjectIngredient<Modules> modulesIngForPlanner; public ComputeJsDepGraph( JsPlanner planner, OptionsIngredient<JsOptions> optionsIng, FileSetIngredient sources) { super( PlanKey.builder("js-module-graph") .addInp(optionsIng, sources) .build(), ImmutableList.<Ingredient>of(optionsIng, sources), Sets.immutableEnumSet(StepSource.JS_GENERATED, StepSource.JS_SRC), Sets.immutableEnumSet(StepSource.JS_COMPILED)); this.planner = planner; } synchronized SerializedObjectIngredient<Modules> getModulesIng() throws IOException { if (modulesIngForPlanner == null) { modulesIngForPlanner = planner.planner.ingredients.serializedObject( new File(new File(planner.planner.outputDir, "js"), "modules.ser"), Modules.class); } return modulesIngForPlanner; } @Override public void execute(Log log) throws MojoExecutionException { OptionsIngredient<JsOptions> optionsIng = ((OptionsIngredient<?>) inputs.get(0)).asSuperType(JsOptions.class); FileSetIngredient sources = (FileSetIngredient) inputs.get(1); Modules modules = execute( log, optionsIng.getOptions(), new CompilerInputFactory() { @Override public CompilerInput create(Source s) { SourceFile sourceFile = new SourceFile.Builder() .withCharset(Charsets.UTF_8) .withOriginalPath(s.relativePath.getPath()) .buildFromFile(s.canonicalPath); return new CompilerInput(sourceFile); } }, Lists.transform(sources.mainSources(), FileIngredient.GET_SOURCE), Lists.transform(sources.testSources(), FileIngredient.GET_SOURCE)); try { SerializedObjectIngredient<Modules> modulesIng = getModulesIng(); modulesIng.setStoredObject(modules); modulesIng.write(); } catch (IOException ex) { throw new MojoExecutionException("Failed to store JS module graph", ex); } } @VisibleForTesting static Modules execute( Log log, JsOptions options, CompilerInputFactory ciFactory, Iterable<? extends Source> mainSources, Iterable<? extends Source> testSources) throws MojoExecutionException { Multimap<ModuleName, CompilerInputAndSource> compilerInputsPerModule = Multimaps.newMultimap( Maps.<ModuleName, Collection<CompilerInputAndSource>>newTreeMap(), new Supplier<Collection<CompilerInputAndSource>>() { @Override public Collection<CompilerInputAndSource> get() { return Sets.newTreeSet( new Comparator<CompilerInputAndSource>() { @Override public int compare( CompilerInputAndSource a, CompilerInputAndSource b) { return a.s.relativePath.compareTo(b.s.relativePath); } }); } }); collectSourceFiles( "main", mainSources, compilerInputsPerModule, ciFactory); collectSourceFiles( "test", testSources, compilerInputsPerModule, ciFactory); final Compiler parsingCompiler = new Compiler( new MavenLogJSErrorManager(log)); parsingCompiler.initOptions(options.toCompilerOptions()); // goog.provide and goog.require are ambiently available. final ImmutableSet<GoogNamespace> ambientlyAvailable = ImmutableSortedSet.of(new GoogNamespace("goog")); TopoSort<ModuleName, GoogNamespace> moduleTopoSort; { Map<ModuleName, Set<GoogNamespace>> allRequires = Maps.newLinkedHashMap(); Map<ModuleName, Set<GoogNamespace>> allProvides = Maps.newLinkedHashMap(); for (Map.Entry<ModuleName, Collection<CompilerInputAndSource>> e : compilerInputsPerModule.asMap().entrySet()) { ModuleName moduleName = e.getKey(); Set<GoogNamespace> reqs = Sets.newTreeSet(); ImmutableSet.Builder<GoogNamespace> provsBuilder = ImmutableSet.builder(); for (CompilerInputAndSource cis : e.getValue()) { cis.ci.setCompiler(parsingCompiler); reqs.addAll(GoogNamespace.allOf(cis.ci.getRequires())); provsBuilder.addAll(GoogNamespace.allOf(cis.ci.getProvides())); } // We don't need to require internally provided symbols. ImmutableSet<GoogNamespace> provs = provsBuilder.build(); reqs.removeAll(provs); allRequires.put(moduleName, ImmutableSet.copyOf(reqs)); allProvides.put(moduleName, provs); } try { moduleTopoSort = new TopoSort<>( Functions.forMap(allRequires), Functions.forMap(allProvides), compilerInputsPerModule.keySet(), ambientlyAvailable); } catch (TopoSort.CyclicRequirementException ex) { throw new MojoExecutionException("Mismatched require/provides", ex); } catch (TopoSort.MissingRequirementException ex) { throw new MojoExecutionException("Mismatched require/provides", ex); } } ImmutableList<ModuleName> moduleOrder = moduleTopoSort.getSortedItems(); // When computing the internal ordering, we don't need to require things // that are provided by dependencies and which are not provided internally. // Since we've already figured out the dependency order, we just keep a // running total of symbols to subtract from the current module's required // set. final Set<GoogNamespace> providedByPossibleDependencies = Sets.newTreeSet(); ImmutableList.Builder<Modules.Module> moduleList = ImmutableList.builder(); for (ModuleName moduleName : moduleOrder) { final Map<String, CompilerInputAndSource> inputsByCiName = Maps.newLinkedHashMap(); Collection<CompilerInputAndSource> moduleSources = compilerInputsPerModule.get(moduleName); for (CompilerInputAndSource cis : moduleSources) { String ciName = cis.ci.getName(); Preconditions.checkState( null == inputsByCiName.put(ciName, cis)); } TopoSort<CompilerInputAndSource, GoogNamespace> compilerInputsTopoSort; try { compilerInputsTopoSort = new TopoSort<>( new Function<CompilerInputAndSource, Collection<GoogNamespace>>() { @Override public Collection<GoogNamespace> apply(CompilerInputAndSource cis) { ImmutableList<GoogNamespace> reqs = GoogNamespace.allOf(cis.ci.getRequires()); ImmutableList.Builder<GoogNamespace> reqsFiltered = ImmutableList.builder(); for (GoogNamespace req : reqs) { if (!providedByPossibleDependencies.contains(req)) { reqsFiltered.add(req); } } return reqsFiltered.build(); } }, new Function<CompilerInputAndSource, Collection<GoogNamespace>>() { @Override public Collection<GoogNamespace> apply(CompilerInputAndSource cis) { return GoogNamespace.allOf(cis.ci.getProvides()); } }, inputsByCiName.values(), ambientlyAvailable); } catch (TopoSort.CyclicRequirementException ex) { throw new MojoExecutionException( "Mismatched require/provides in module " + moduleName, ex); } catch (TopoSort.MissingRequirementException ex) { throw new MojoExecutionException( "Mismatched require/provides in module " + moduleName, ex); } ImmutableList<ModuleName> orderedDeps = moduleTopoSort.getDependenciesTransitive(moduleName); ImmutableList.Builder<Source> orderedSources = ImmutableList.builder(); for (CompilerInputAndSource cis : compilerInputsTopoSort.getSortedItems()) { orderedSources.add(cis.s); providedByPossibleDependencies.addAll( GoogNamespace.allOf(cis.ci.getProvides())); } // Build a Module with the inputs in topo-order. Modules.Module module = new Modules.Module( moduleName.text, ImmutableList.copyOf( Lists.transform(orderedDeps, Identifier.GET_TEXT)), orderedSources.build()); moduleList.add(module); } return new Modules(moduleList.build()); } @Override public void skip(Log log) throws MojoExecutionException { try { getModulesIng().read(); } catch (IOException ex) { throw new MojoExecutionException("Failed to load JS module graph", ex); } } @Override public ImmutableList<Step> extraSteps(Log log) throws MojoExecutionException { OptionsIngredient<JsOptions> optionsIng = ((OptionsIngredient<?>) inputs.get(0)).asSuperType(JsOptions.class); CommonPlanner commonPlanner = planner.planner; PathValue jsOutputDir = commonPlanner.ingredients.pathValue( new File(commonPlanner.projectBuildOutputDirectory.value, "js")); try { return ImmutableList.<Step>of( new CompileJs( optionsIng, getModulesIng(), jsOutputDir)); } catch (IOException ex) { throw new MojoExecutionException("Could not find JS module graph", ex); } } private static void collectSourceFiles( String moduleNamePrefix, Iterable<? extends Source> sources, Multimap<ModuleName, CompilerInputAndSource> sourceFilesByModuleName, CompilerInputFactory ciFactory) { for (Source s : sources) { File parentRelPath = s.relativePath.getParentFile(); ModuleName moduleName; if (parentRelPath != null) { moduleName = new ModuleName( moduleNamePrefix + "." + parentRelPath.getPath().replaceAll("[/\\\\]", ".")); } else { moduleName = new ModuleName(moduleNamePrefix); } CompilerInput ci = ciFactory.create(s); sourceFilesByModuleName.put( moduleName, new CompilerInputAndSource(ci, s)); } } static final class CompilerInputAndSource implements Comparable<CompilerInputAndSource> { final CompilerInput ci; final Source s; CompilerInputAndSource(CompilerInput ci, Source s) { this.ci = ci; this.s = s; } @Override public int compareTo(CompilerInputAndSource that) { return this.s.canonicalPath.compareTo(that.s.canonicalPath); } @Override public String toString() { return "{Source " + s.canonicalPath + "}"; } } interface CompilerInputFactory { CompilerInput create(Source source); } static abstract class Identifier implements Comparable<Identifier>, Serializable { private static final long serialVersionUID = -5072636170709799520L; final String text; static final Function<Identifier, String> GET_TEXT = new Function<Identifier, String>() { @Override public String apply(Identifier id) { return id.text; } }; Identifier(String text) { this.text = Preconditions.checkNotNull(text); } @Override public final boolean equals(Object o) { if (o == null || o.getClass() != getClass()) { return false; } return text.equals(((Identifier) o).text); } @Override public final int hashCode() { return text.hashCode(); } @Override public final int compareTo(Identifier that) { return this.text.compareTo(that.text); } @Override public String toString() { return "{" + getClass().getSimpleName() + " " + text + "}"; } } static final class ModuleName extends Identifier { private static final long serialVersionUID = 5721482936852117897L; ModuleName(String text) { super(text); } } static final class GoogNamespace extends Identifier { private static final long serialVersionUID = -4018457478547773405L; GoogNamespace(String text) { super(text); } static ImmutableList<GoogNamespace> allOf(Iterable<? extends String> xs) { ImmutableList.Builder<GoogNamespace> b = ImmutableList.builder(); for (String x : xs) { b.add(new GoogNamespace(x)); } return b.build(); } } }
package com.googlecode.loosejar.output; import java.util.List; import java.util.Map; import com.googlecode.loosejar.ClassLoaderAnalyzer; import com.googlecode.loosejar.JarArchive; public class CSVFormatSummarizer implements Summarizer { private StringBuilder builder = null; public CSVFormatSummarizer() { super(); } private void writeHeader() { builder.append("ClassLoader Name,"); builder.append("Jar,"); builder.append("Utilization,"); builder.append("Loaded Classes,"); builder.append("Total Classes"); builder.append("\n"); } private void writeSummaryForJar(ClassLoader classLoader, JarArchive jar) { builder.append((String.format("%s,%s,%.2f%%,%d,%d\n", classLoader.getClass().getName(), jar.getJar(), jar.getUsagePercentage(), jar.getNamesOfLoadedClasses().size(), jar.getAllClassNames().size()))); } public String summarize(Map<ClassLoader, List<String>> classLoaderToClassListMap) { builder = new StringBuilder(""); writeHeader(); for (ClassLoader ucl : classLoaderToClassListMap.keySet()) { ClassLoaderAnalyzer classLoaderAnalyzer = new ClassLoaderAnalyzer(ucl, classLoaderToClassListMap.get(ucl)); classLoaderAnalyzer.analyze(); List<JarArchive> jarList = classLoaderAnalyzer.getJars(); writeSummaryForClassloader(ucl, jarList); } return builder.toString(); } private void writeSummaryForClassloader(ClassLoader classLoader, List<JarArchive> jarList) { for (JarArchive jarArchive : jarList) { writeSummaryForJar(classLoader, jarArchive); } } }
package com.horsefire.tiddly.tiddlybox; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.basic.DefaultOAuthConsumer; import oauth.signpost.basic.DefaultOAuthProvider; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Singleton; @SuppressWarnings("serial") @Singleton public class HandshakeOneServlet extends HttpServlet { private static final Logger LOG = LoggerFactory .getLogger(HandshakeOneServlet.class); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { final UserPreferences prefs = UserPreferences.get(req); final OAuthConsumer consumer = new DefaultOAuthConsumer( DropboxWikiClient.VALUE_CONSUMER_KEY, DropboxWikiClient.VALUE_CONSUMER_SECRET); final OAuthProvider provider = new DefaultOAuthProvider( DropboxWikiClient.VALUE_REQUEST_TOKEN_URL, DropboxWikiClient.VALUE_ACCESS_TOKEN_URL, DropboxWikiClient.VALUE_AUTHORIZATION_URL); try { String host = "http://" + req.getServerName(); if (req.getServerPort() != 80) { host = host + ':' + req.getLocalPort(); } final String url = provider.retrieveRequestToken(consumer, (host + req.getContextPath()) + BootstrapListener.HANDSHAKE_TWO_URL); prefs.setOauthTokenKey(consumer.getToken()); prefs.setOauthTokenSecret(consumer.getTokenSecret()); resp.sendRedirect(url); } catch (OAuthMessageSignerException e) { error(resp, e); } catch (OAuthNotAuthorizedException e) { error(resp, e); } catch (OAuthExpectationFailedException e) { error(resp, e); } catch (OAuthCommunicationException e) { error(resp, e); } } private void error(HttpServletResponse resp, Exception e) throws IOException { String message = "Failure during part one of handshake"; resp.getWriter().print(message); LOG.error(message, e); } }
package com.lothrazar.cyclicmagic.guideapi; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import com.lothrazar.cyclicmagic.data.Const; import com.lothrazar.cyclicmagic.registry.GuideRegistry; import com.lothrazar.cyclicmagic.registry.GuideRegistry.GuideCategory; import com.lothrazar.cyclicmagic.registry.GuideRegistry.GuideItem; import com.lothrazar.cyclicmagic.registry.GuideRegistry.GuidePage; import com.lothrazar.cyclicmagic.registry.RecipeRegistry; import com.lothrazar.cyclicmagic.util.UtilChat; import amerifrance.guideapi.api.GuideAPI; import amerifrance.guideapi.api.GuideBook; import amerifrance.guideapi.api.IGuideBook; import amerifrance.guideapi.api.IPage; import amerifrance.guideapi.api.impl.Book; import amerifrance.guideapi.api.impl.abstraction.CategoryAbstract; import amerifrance.guideapi.api.impl.abstraction.EntryAbstract; import amerifrance.guideapi.api.util.PageHelper; import amerifrance.guideapi.category.CategoryItemStack; import amerifrance.guideapi.entry.EntryItemStack; import amerifrance.guideapi.page.PageBrewingRecipe; import amerifrance.guideapi.page.PageIRecipe; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.Optional; import net.minecraftforge.oredict.ShapedOreRecipe; @Optional.Interface(iface = "amerifrance.guideapi.api.GuideAPI", modid = "guideapi", striprefs = true) @GuideBook public class CyclicGuideBook implements IGuideBook { private static final String GUIDE_API_MOD_ID = "guideapi"; private static final int MAX_PAGE_LENGTH = 314; private static Book book; private List<CategoryAbstract> categories = new ArrayList<CategoryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesBlocks = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesItems = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesGear = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesWorld = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesEnchants = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesBlockMachine = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesBlockPlate = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesItemBaubles = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesItemThrow = new HashMap<ResourceLocation, EntryAbstract>(); private Map<ResourceLocation, EntryAbstract> entriesTransport = new HashMap<ResourceLocation, EntryAbstract>(); private void addEntry(GuideCategory cat, List<IPage> page, String pageTitle, ItemStack icon) { switch (cat) { case BLOCK: entriesBlocks.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case ITEM: entriesItems.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case GEAR: entriesGear.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case WORLD: entriesWorld.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case ENCHANT: entriesEnchants.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case BLOCKMACHINE: entriesBlockMachine.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case BLOCKPLATE: entriesBlockPlate.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case ITEMBAUBLES: entriesItemBaubles.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case ITEMTHROW: entriesItemThrow.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; case TRANSPORT: entriesTransport.put(new ResourceLocation(Const.MODID, pageTitle), new EntryItemStack(page, pageTitle, icon)); break; default: break; } } private void buildPages() { List<GuideItem> items = GuideRegistry.getItems(); Comparator<GuideItem> comparator = new Comparator<GuideItem>() { @Override public int compare(final GuideItem first, final GuideItem second) { return first.title.compareTo(second.title); } }; Collections.sort(items, comparator); for (GuideItem item : items) { List<IPage> pages = new ArrayList<IPage>(); for (GuidePage p : item.pages) { if (p.text != null) { for (IPage textPage : PageHelper.pagesForLongText(p.text, MAX_PAGE_LENGTH)) { pages.add(textPage); } } if (p.recipe != null) { pages.add(new PageIRecipe(p.recipe)); } if (p.brewRecipe != null) { pages.add(new PageBrewingRecipe(p.brewRecipe)); } } if (item.cat == null) { item.cat = GuideCategory.WORLD; } addEntry(item.cat, pages, item.title, new ItemStack(item.icon)); } } @Override public Book buildBook() { buildPages(); buildCategories(); buildBookItem(); return book; } private void buildCategories() { addCategory(entriesBlocks, GuideCategory.BLOCK); addCategory(entriesBlockMachine, GuideCategory.BLOCKMACHINE); addCategory(entriesItems, GuideCategory.ITEM); addCategory(entriesGear, GuideCategory.GEAR); // addCategory(entriesPotion, GuideCategory.POTION); addCategory(entriesEnchants, GuideCategory.ENCHANT); addCategory(entriesWorld, GuideCategory.WORLD); addCategory(entriesBlockPlate, GuideCategory.BLOCKPLATE); addCategory(entriesItemBaubles, GuideCategory.ITEMBAUBLES); addCategory(entriesItemThrow, GuideCategory.ITEMTHROW); addCategory(entriesTransport, GuideCategory.TRANSPORT); } private void addCategory(Map<ResourceLocation, EntryAbstract> entriesBlockPlate, GuideCategory cat) { categories.add(new CategoryItemStack(entriesBlockPlate, cat.text(), cat.icon())); } private void buildBookItem() { book = new Book(); book.setTitle("guide.title"); book.setDisplayName(UtilChat.lang("item.guide.name")); book.setWelcomeMessage(UtilChat.lang("guide.welcome")); book.setAuthor("Lothrazar"); book.setColor(Color.MAGENTA); book.setCategoryList(categories); book.setRegistryName(new ResourceLocation(Const.MODID, "guide")); book.setSpawnWithBook(true); } @Override public void handleModel(ItemStack bookStack) { GuideAPI.setModel(book); // ResourceLocation location = new ResourceLocation(GUIDE_API_MOD_ID, Const.MODID + "_guidebook"); // IRecipe recipe = new ShapedOreRecipe(location, bookStack, // "coc", // 'c', Blocks.COBBLESTONE_WALL, // 'b', Items.BOOK, // 'o', Blocks.GRAVEL, // 's', Items.STICK); // //replace with guideapi prefix // // we get a forge warning if using cyclic mod id, since recipe base doesnt match item base // RecipeRegistry.add(recipe, location); } @Override public void handlePost(ItemStack bookStack) { // recipe used to work in handle post, had to move into handleModel in 1.12 } }
package com.netflix.elasticcar.backup; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import com.netflix.elasticcar.backup.exception.RestoreBackupException; import com.netflix.elasticcar.configuration.IConfiguration; import com.netflix.elasticcar.scheduler.SimpleTimer; import com.netflix.elasticcar.scheduler.Task; import com.netflix.elasticcar.scheduler.TaskTimer; import com.netflix.elasticcar.utils.ESTransportClient; import com.netflix.elasticcar.utils.ElasticsearchProcessMonitor; import com.netflix.elasticcar.utils.EsUtils; import com.netflix.elasticcar.utils.HttpModule; import org.apache.commons.lang.StringUtils; import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.rest.RestStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @Singleton public class RestoreBackupManager extends Task { private static final Logger logger = LoggerFactory.getLogger(RestoreBackupManager.class); public static String JOBNAME = "RestoreBackupManager"; private final AbstractRepository repository; private final HttpModule httpModule; private static final AtomicBoolean isRestoreRunning = new AtomicBoolean(false); private static final String ALL_INDICES_TAG = "_all"; private static final String SUFFIX_SEPARATOR_TAG = "-"; @Inject public RestoreBackupManager(IConfiguration config, @Named("s3")AbstractRepository repository, HttpModule httpModule) { super(config); this.repository = repository; this.httpModule = httpModule; } @Override public void execute() { try { //Confirm if Current Node is a Master Node if (EsUtils.amIMasterNode(config,httpModule)) { // If Elasticsearch is started then only start Snapshot Backup if (!ElasticsearchProcessMonitor.isElasticsearchStarted()) { String exceptionMsg = "Elasticsearch is not yet started, hence not Starting Restore Operation"; logger.info(exceptionMsg); return; } logger.info("Current node is the Master Node. Running Restore now ..."); runRestore(config.getRestoreRepositoryName(), config.getRestoreRepositoryType(), config.getRestoreSnapshotName(), config.getCommaSeparatedIndicesToRestore()); } else { logger.info("Current node is not a Master Node yet, hence not running a Restore"); } } catch (Exception e) { logger.warn("Exception thrown while running Restore Backup", e); } } public void runRestore(String repositoryName, String repositoryType, String snapshotName, String indices) throws Exception { TransportClient esTransportClient = ESTransportClient.instance(config).getTransportClient(); // Get Repository Name String repoN = StringUtils.isBlank(repositoryName) ? config.getRestoreRepositoryName() : repositoryName; if(StringUtils.isBlank(repoN)) throw new RestoreBackupException("Repository Name is Null or Empty"); //Attach suffix to the repository name so that it does not conflict with Snapshot Repository name String repoWithSuffix = repoN + SUFFIX_SEPARATOR_TAG + config.getRestoreSourceClusterName(); String repoType = StringUtils.isBlank(repositoryType) ? config.getRestoreRepositoryType().toLowerCase() : repositoryType; if(StringUtils.isBlank(repoType)) { logger.info("RepositoryType is empty, hence Defaulting to <s3> type"); repoType = AbstractRepository.RepositoryType.s3.name(); } if(!repository.doesRepositoryExists(repoWithSuffix, AbstractRepository.RepositoryType.valueOf(repoType.toLowerCase()))) { //If repository does not exist, create new one repository.createRestoreRepository(repoWithSuffix,repoN); } // Get Snapshot Name String snapshotN = StringUtils.isBlank(snapshotName) ? config.getRestoreSnapshotName() : snapshotName; if(StringUtils.isBlank(snapshotN)) { //Pick the last Snapshot from the available Snapshots List<String> snapshots = EsUtils.getAvailableSnapshots(esTransportClient,repoN); if(snapshots.isEmpty()) throw new RestoreBackupException("No available snapshots in <"+repoN+"> repository."); //Sorting Snapshot names in Reverse Order Collections.sort(snapshots,Collections.reverseOrder()); //Use the Last available snapshot snapshotN = snapshots.get(0); } logger.info("Snapshot Name : <"+snapshotN+">"); // Get Names of Indices String commaSeparatedIndices = StringUtils.isBlank(indices) ? config.getCommaSeparatedIndicesToRestore() : indices; if(StringUtils.isBlank(commaSeparatedIndices) || commaSeparatedIndices.equalsIgnoreCase(ALL_INDICES_TAG)) { commaSeparatedIndices = null; logger.info("Restoring all Indices."); } logger.info("Indices param : <"+commaSeparatedIndices+">"); //This is a blocking call. It'll wait until Restore is finished. RestoreSnapshotResponse restoreSnapshotResponse = esTransportClient.admin().cluster().prepareRestoreSnapshot(repoN, snapshotN) .setWaitForCompletion(true) .setIndices(commaSeparatedIndices) //"test-idx-*", "-test-idx-2" .execute() .actionGet(); logger.info("Restore Status = "+restoreSnapshotResponse.status().toString()); if(restoreSnapshotResponse.status() == RestStatus.OK) { printRestoreDetails(restoreSnapshotResponse); } else if (restoreSnapshotResponse.status() == RestStatus.INTERNAL_SERVER_ERROR) logger.info("Snapshot Completely Failed"); } //TODO: Map to Java Class and Create JSON public void printRestoreDetails(RestoreSnapshotResponse restoreSnapshotResponse) { StringBuilder builder = new StringBuilder(); builder.append("Restore Details:"); builder.append("\n\t Name = "+restoreSnapshotResponse.getRestoreInfo().name()); builder.append("\n\t Indices : "); for(String index:restoreSnapshotResponse.getRestoreInfo().indices()) { builder.append("\n\t\t Index = "+index); } builder.append("\n\t Total Shards = "+restoreSnapshotResponse.getRestoreInfo().totalShards()); builder.append("\n\t Successful Shards = "+restoreSnapshotResponse.getRestoreInfo().successfulShards()); builder.append("\n\t Total Failed Shards = "+restoreSnapshotResponse.getRestoreInfo().failedShards()); logger.info(builder.toString()); } public static TaskTimer getTimer(IConfiguration config) { return new SimpleTimer(JOBNAME); } @Override public String getName() { return JOBNAME; } }